Create ASP.NET Core Web API Project Using Code First Approach
Create ASP.NET Core Web API Project Using Code First Approach
Here’s a step-by-step guide to creating a CRUD (Create, Read, Update, Delete) operation using the Code-First approach in ASP.NET Core Web API.
Step 1: Create a new ASP.NET Core Web API Project
- Open Visual Studio.
- Click on Create a new project.
- Select ASP.NET Core Web API and click Next.
- Provide the project name and location, then click Create.
- Select the .NET Core framework and choose ASP.NET Core 7.0 (or latest version). Make sure Enable OpenAPI support is checked.
Step 2: Install Entity Framework Core Packages
- Right-click on your project in Solution Explorer and select Manage NuGet Packages.
- Install the following packages:
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Microsoft.EntityFrameworkCore
Step 3: Create the Model
Create a simple model class for an entity, like Product
.
namespace WebApiCrud.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Step 4: Create the Database Context
Add a class for the DbContext which will manage the database operations.
using Microsoft.EntityFrameworkCore;
namespace WebApiCrud.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
}
Step 5: Configure the Database Connection String
In the appsettings.json
file, add your database connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-9M9EDAA\\SQLEXPRESS;Database=EShopeDB;
Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Step 6: Configure the Application to Use EF Core
Open Program.cs
and configure the services to use the database context and connection string.
using WebApiCrud.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Add DB context and connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 7: Add Migrations and Update the Database
- Open Package Manager Console and run the following commands:
Add-Migration InitialCreate Update-Database
- This will create the database and the
Products
table in SQL Server.
Step 8: Create a Controller for CRUD Operations
Add a controller to handle CRUD operations.
using Microsoft.AspNetCore.Mvc;
using WebApiCrud.Data;
using WebApiCrud.Models;
using Microsoft.EntityFrameworkCore;
namespace WebApiCrud.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public ProductsController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
// GET: api/products/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return product;
}
// POST: api/products
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest();
}
_context.Entry(product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// DELETE: api/products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
private bool ProductExists(int id)
{
return _context.Products.Any(e => e.Id == id);
}
}
}
Step 9: Test the API
You can test the API using tools like Postman or Swagger (which is enabled by default). You can:
- GET:
https://localhost:5001/api/products
to retrieve all products. - POST:
https://localhost:5001/api/products
with a JSON body to add a new product. - PUT:
https://localhost:5001/api/products/{id}
to update an existing product. - DELETE:
https://localhost:5001/api/products/{id}
to delete a product.
Final Steps
- Run your application.
- Use Swagger at
/swagger/index.html
to interact with your API.
This is a basic CRUD implementation using the Code-First approach in ASP.NET Core Web API.
----------------------------------------------------------------------------------------------------------------------
Consume the Web API in a .NET Core Application
To integrate the ASP.NET Core Web API CRUD operations into a .NET Core app (such as an ASP.NET Core MVC or Razor Pages app), you need to consume the API by making HTTP requests from your application. Here's how to do it step by step.
Steps to Consume the Web API in a .NET Core Application:
1. Create a .NET Core MVC Application
- Open Visual Studio.
- Go to File > New > Project.
- Select ASP.NET Core Web App (Model-View-Controller) and click Next.
- Name your project (e.g.,
MvcApp
) and click Create. - Select .NET 7.0 or .NET 6.0 and click Create.
2. Install the Required NuGet Packages
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson
for handling JSON serialization/deserialization and System.Net.Http.Json
for working with HTTP requests:
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
3. Create a Service to Interact with the Web API
You will create a service class that interacts with the Web API using HttpClient
.
- Create a folder named Services in your project.
- Inside the Services folder, create a new class named
EmployeeService.cs
.
Example: EmployeeService.cs
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using MvcApp.Models; // Import your models here
using System.Collections.Generic;
namespace MvcApp.Services
{
public class EmployeeService
{
private readonly HttpClient _httpClient;
public EmployeeService(HttpClient httpClient)
{
_httpClient = httpClient;
}
// Get all employees
public async Task<List<Employee>> GetEmployeesAsync()
{
return await _httpClient.GetFromJsonAsync<List<Employee>>("api/Employees");
}
// Get employee by ID
public async Task<Employee> GetEmployeeByIdAsync(int id)
{
return await _httpClient.GetFromJsonAsync<Employee>($"api/Employees/{id}");
}
// Create a new employee
public async Task CreateEmployeeAsync(Employee employee)
{
await _httpClient.PostAsJsonAsync("api/Employees", employee);
}
// Update an existing employee
public async Task UpdateEmployeeAsync(int id, Employee employee)
{
await _httpClient.PutAsJsonAsync($"api/Employees/{id}", employee);
}
// Delete an employee
public async Task DeleteEmployeeAsync(int id)
{
await _httpClient.DeleteAsync($"api/Employees/{id}");
}
}
}
4. Configure Dependency Injection for HttpClient
In your Program.cs
, configure the HttpClient
for dependency injection to use in your service class.
Modify Program.cs
to include the EmployeeService
:
var builder = WebApplication.CreateBuilder(args);
// Register HttpClient with the base address of your Web API
builder.Services.AddHttpClient<EmployeeService>(client =>
{
client.BaseAddress = new Uri("https://localhost:5001/"); // Your Web API's base URL
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
5. Create Views and Controllers to Display Data
a) Create a Model
Create a folder named Models and add a model class Employee.cs
that matches the structure of the employee data from the Web API.
namespace MvcApp.Models
{
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public decimal Salary { get; set; }
// Other fields as per your database schema
}
}
b) Create a Controller
- Right-click on the Controllers folder and select Add > Controller > MVC Controller - Empty.
- Name it
EmployeeController.cs
.
Example: EmployeeController.cs
using Microsoft.AspNetCore.Mvc;
using MvcApp.Services;
using MvcApp.Models;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace MvcApp.Controllers
{
public class EmployeeController : Controller
{
private readonly EmployeeService _employeeService;
public EmployeeController(EmployeeService employeeService)
{
_employeeService = employeeService;
}
// Display all employees
public async Task<IActionResult> Index()
{
var employees = await _employeeService.GetEmployeesAsync();
return View(employees);
}
// View details of a single employee
public async Task<IActionResult> Details(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
return View(employee);
}
// Create a new employee (GET)
public IActionResult Create()
{
return View();
}
// Create a new employee (POST)
[HttpPost]
public async Task<IActionResult> Create(Employee employee)
{
if (ModelState.IsValid)
{
await _employeeService.CreateEmployeeAsync(employee);
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// Edit an employee (GET)
public async Task<IActionResult> Edit(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
return View(employee);
}
// Edit an employee (POST)
[HttpPost]
public async Task<IActionResult> Edit(int id, Employee employee)
{
if (ModelState.IsValid)
{
await _employeeService.UpdateEmployeeAsync(id, employee);
return RedirectToAction(nameof(Index));
}
return View(employee);
}
// Delete an employee (GET)
public async Task<IActionResult> Delete(int id)
{
var employee = await _employeeService.GetEmployeeByIdAsync(id);
return View(employee);
}
// Delete an employee (POST)
[HttpPost, ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
await _employeeService.DeleteEmployeeAsync(id);
return RedirectToAction(nameof(Index));
}
}
}
c) Create Views for Employee
- Right-click the Views folder, add a folder named Employee, and add the following views:
Index.cshtml
,Create.cshtml
,Edit.cshtml
,Details.cshtml
, andDelete.cshtml
.
Example: Index.cshtml
@model IEnumerable<MvcApp.Models.Employee>
<h2>Employees List</h2>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var employee in Model)
{
<tr>
<td>@employee.Name</td>
<td>@employee.Position</td>
<td>@employee.Salary</td>
<td>
<a href="@Url.Action("Details", "Employee", new { id = employee.EmployeeId })">Details</a> |
<a href="@Url.Action("Edit", "Employee", new { id = employee.EmployeeId })">Edit</a> |
<a href="@Url.Action("Delete", "Employee", new { id = employee.EmployeeId })">Delete</a>
</td>
</tr>
}
</tbody>
</table>
<a href="@Url.Action("Create", "Employee")" class="btn btn-primary">Create New</a>
6. Run the Application
Now, when you run your .NET Core MVC
app, you will see a list of employees fetched from the Web API. You can also create, edit, and delete employees by interacting with the API through the app.
This demonstrates how to consume a Web API in a .NET Core MVC application using HttpClient.
No comments: