Build a Web API with ASP.NET Core and Entity Framework

Build a Web API with ASP.NET Core and Entity Framework

Build a Web API with ASP.NET Core and Entity Framework

Build a production-ready Web API using ASP.NET Core — the industry-standard approach for C# back-end development.

Features

  • RESTful endpoints with ASP.NET Core controllers
  • Entity Framework Core with SQL Server / SQLite
  • Repository pattern for data access
  • JWT Bearer authentication
  • Swagger / OpenAPI documentation
  • Global error handling middleware

Step 1 — Project Setup

dotnet new webapi -n ProductApi --use-controllers
cd ProductApi
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Swashbuckle.AspNetCore

Step 2 — Model & DbContext

public class Product
{
    public int     Id       { get; set; }
    public string  Name     { get; set; } = string.Empty;
    public decimal Price    { get; set; }
    public int     Stock    { get; set; }
}

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();
}

Step 3 — Repository

public interface IProductRepository
{
    Task<IEnumerable<Product>> GetAllAsync();
    Task<Product?>             GetByIdAsync(int id);
    Task                        AddAsync(Product product);
    Task                        UpdateAsync(Product product);
    Task                        DeleteAsync(int id);
}

public class ProductRepository(AppDbContext db) : IProductRepository
{
    public Task<IEnumerable<Product>> GetAllAsync() =>
        Task.FromResult<IEnumerable<Product>>(db.Products.AsEnumerable());

    public async Task<Product?> GetByIdAsync(int id) =>
        await db.Products.FindAsync(id);

    public async Task AddAsync(Product product)
    {
        db.Products.Add(product);
        await db.SaveChangesAsync();
    }

    public async Task UpdateAsync(Product product)
    {
        db.Products.Update(product);
        await db.SaveChangesAsync();
    }

    public async Task DeleteAsync(int id)
    {
        var product = await db.Products.FindAsync(id);
        if (product is not null) { db.Products.Remove(product); await db.SaveChangesAsync(); }
    }
}

Step 4 — Controller

[ApiController]
[Route("api/products")]
[Authorize]
public class ProductsController(IProductRepository repo) : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetAll() =>
        Ok(await repo.GetAllAsync());

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id)
    {
        var product = await repo.GetByIdAsync(id);
        return product is null ? NotFound() : Ok(product);
    }

    [HttpPost]
    public async Task<IActionResult> Create(Product product)
    {
        await repo.AddAsync(product);
        return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(int id)
    {
        await repo.DeleteAsync(id);
        return NoContent();
    }
}
All Comments