ASP.NET Core 10 Web API: Build a Production-Ready API From Scratch (2027 Guide)
Most ASP.NET Core Web API tutorials stop at "it runs on my machine." You get a WeatherForecastController, a happy-path GET endpoint, and nothing about what happens when real users, real data and real errors show up. Then you ship it, and the missing pieces — validation, consistent error responses, logging, authentication — get bolted on one painful incident at a time.
This asp.net core web api tutorial is different. We will build a small product catalog API in .NET 10, but we will build it the way I structure APIs that actually go to production for clients: DTOs between the wire and the database, global error handling with ProblemDetails, Serilog logging that is useful at 2 AM, JWT authentication, and a deployment checklist at the end. If you follow it start to finish, you will not just have a working API — you will have the skeleton I reuse on almost every new project.
You need the .NET 10 SDK installed and a SQL Server instance you can connect to (LocalDB or a Docker container is fine). Basic C# knowledge is assumed; no prior ASP.NET Core experience is required.
What we are building and the final project structure
We are building a ProductCatalog API: products with categories, prices and stock levels, exposed over REST with full CRUD. Small enough to finish in one sitting, realistic enough to force every production decision that matters.
Here is the structure we will end with:
ProductCatalog.Api/
├── Controllers/
│ └── ProductsController.cs
├── Data/
│ └── AppDbContext.cs
├── Dtos/
│ ├── ProductDto.cs
│ └── CreateProductRequest.cs
├── Errors/
│ └── GlobalExceptionHandler.cs
├── Models/
│ └── Product.cs
├── Services/
│ └── ProductService.cs
├── Program.cs
└── appsettings.jsonA few opinions baked into this layout, learned the hard way:
- DTOs live separately from entities. Your database model and your API contract change for different reasons. Coupling them means a harmless column rename breaks your mobile app.
- Business logic goes in services, not controllers. Controllers translate HTTP to method calls and back. The moment a controller touches
DbContextdirectly, testing and reuse both get harder. - One project is fine. You do not need five projects and Clean Architecture for a catalog API. Start simple; split when the pain is real, not imagined.
This post is the pillar guide for a whole series. Error handling, authentication and health checks each get a deep-dive post of their own, linked throughout — this one gives you the complete working picture.
Create the project and configure the pipeline
Create the project and add the packages we need:
dotnet new webapi -n ProductCatalog.Api --use-controllers
cd ProductCatalog.Api
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Serilog.AspNetCore
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerI use --use-controllers here because controllers are still the clearest way to learn the request pipeline, and most production codebases you will join use them. (Minimal APIs are a fine choice too — I compare them honestly in a separate post.)
Now the important part: Program.cs. The middleware pipeline order matters more than almost anything else in this file. A production-shaped version looks like this:
using Microsoft.EntityFrameworkCore;
using ProductCatalog.Api.Data;
using ProductCatalog.Api.Errors;
using ProductCatalog.Api.Services;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Logging first, so even startup errors are captured
builder.Host.UseSerilog((context, config) =>
config.ReadFrom.Configuration(context.Configuration));
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddScoped<ProductService>();
var app = builder.Build();
app.UseSerilogRequestLogging();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();Two things to notice. First, UseExceptionHandler() sits near the top of the pipeline — it can only catch exceptions from middleware registered after it, so anything above it that throws will produce an ugly default error. Second, UseAuthentication() always comes before UseAuthorization(). Swapping them is a classic beginner bug that produces mysterious 401/403 responses.
EF Core with SQL Server: models, DbContext, migrations
Our entity is deliberately boring:
namespace ProductCatalog.Api.Models;
public class Product
{
public int Id { get; set; }
public required string Name { get; set; }
public string? Description { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
public string Category { get; set; } = "General";
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
}The DbContext registers it and sets one sensible constraint — money should never be a floating point type, and EF Core needs to know the precision you want:
using Microsoft.EntityFrameworkCore;
using ProductCatalog.Api.Models;
namespace ProductCatalog.Api.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.Property(p => p.Price)
.HasPrecision(18, 2);
modelBuilder.Entity<Product>()
.HasIndex(p => p.Category);
}
}Add the connection string to appsettings.json (for local development only — production secrets belong in environment variables or a secret store, never in source control):
{
"ConnectionStrings": {
"Default": "Server=(localdb)\\mssqllocaldb;Database=ProductCatalog;Trusted_Connection=True;TrustServerCertificate=True"
}
}Create and apply the first migration:
dotnet ef migrations add InitialCreate
dotnet ef database updateOne production note: never let the app run database update automatically on startup in a real deployment. Migrations against production should be a deliberate, reviewed step in your release pipeline, so a bad migration never takes the site down at 3 AM during an app pool recycle. (If you want the deep version of working with EF Core efficiently, I wrote a separate guide on optimizing EF Core queries for faster performance — read it once your API works and you want it fast.)
CRUD endpoints with DTOs (never expose entities)
Here is the rule I do not break on client projects: an EF Core entity never crosses the API boundary. Entities contain internal fields, navigation properties that serialize into loops, and columns you have not decided to make public yet. DTOs fix all three problems.
namespace ProductCatalog.Api.Dtos;
public record ProductDto(
int Id,
string Name,
string? Description,
decimal Price,
int Stock,
string Category);
public record CreateProductRequest(
string Name,
string? Description,
decimal Price,
int Stock,
string Category);Records are perfect for DTOs: immutable, concise, and equality works the way you expect. The service holds the mapping and the queries — note the AsNoTracking() on reads and the projection straight into the DTO, so EF Core only selects the columns the API actually returns:
using Microsoft.EntityFrameworkCore;
using ProductCatalog.Api.Data;
using ProductCatalog.Api.Dtos;
using ProductCatalog.Api.Models;
namespace ProductCatalog.Api.Services;
public class ProductService(AppDbContext db)
{
public async Task<List<ProductDto>> GetAllAsync(CancellationToken ct) =>
await db.Products
.AsNoTracking()
.OrderBy(p => p.Name)
.Select(p => new ProductDto(p.Id, p.Name, p.Description, p.Price, p.Stock, p.Category))
.ToListAsync(ct);
public async Task<ProductDto?> GetByIdAsync(int id, CancellationToken ct)
{
var product = await db.Products.AsNoTracking().FirstOrDefaultAsync(p => p.Id == id, ct);
return product is null ? null
: new ProductDto(product.Id, product.Name, product.Description, product.Price, product.Stock, product.Category);
}
public async Task<ProductDto> CreateAsync(CreateProductRequest request, CancellationToken ct)
{
var product = new Product
{
Name = request.Name,
Description = request.Description,
Price = request.Price,
Stock = request.Stock,
Category = request.Category
};
db.Products.Add(product);
await db.SaveChangesAsync(ct);
return new ProductDto(product.Id, product.Name, product.Description, product.Price, product.Stock, product.Category);
}
}The controller is now thin — HTTP in, HTTP out, correct status codes:
using Microsoft.AspNetCore.Mvc;
using ProductCatalog.Api.Dtos;
using ProductCatalog.Api.Services;
namespace ProductCatalog.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
public class ProductsController(ProductService service) : ControllerBase
{
[HttpGet]
public async Task<ActionResult<List<ProductDto>>> GetAll(CancellationToken ct) =>
Ok(await service.GetAllAsync(ct));
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductDto>> GetById(int id, CancellationToken ct)
{
var product = await service.GetByIdAsync(id, ct);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
public async Task<ActionResult<ProductDto>> Create(CreateProductRequest request, CancellationToken ct)
{
var created = await service.CreateAsync(request, ct);
return CreatedAtAction(nameof(GetById), new { id = created.Id }, created);
}
}Notice CreatedAtAction returns 201 with a Location header pointing at the new resource. Small detail, but API consumers notice when you get HTTP semantics right — and returning 200 for everything is one of the most common signs of a tutorial-grade API.
Validation, global error handling and ProblemDetails
Right now, a client can POST a product with a negative price and an empty name, and EF Core will happily save it. Add validation rules to the request DTO:
using System.ComponentModel.DataAnnotations;
public record CreateProductRequest(
[Required, StringLength(120, MinimumLength = 2)] string Name,
[StringLength(1000)] string? Description,
[Range(0.01, 999999)] decimal Price,
[Range(0, int.MaxValue)] int Stock,
[Required, StringLength(60)] string Category);Because the controller has [ApiController], invalid requests are rejected automatically with a 400 response in ProblemDetails format — no code needed. But automatic validation only covers the request shape. What about unhandled exceptions? Without a handler, ASP.NET Core returns an empty 500 (or worse, a stack trace in Development). The production answer is a single global exception handler implementing IExceptionHandler, registered earlier in Program.cs:
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace ProductCatalog.Api.Errors;
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
logger.LogError(exception, "Unhandled exception on {Method} {Path}",
httpContext.Request.Method, httpContext.Request.Path);
var problem = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "An unexpected error occurred.",
Type = "https://datatracker.ietf.org/doc/html/rfc9110#section-15.6.1",
Instance = httpContext.Request.Path
};
httpContext.Response.StatusCode = problem.Status.Value;
await httpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
return true;
}
}Now every error your API produces — validation failures, 404s you return deliberately, and unexpected 500s — speaks the same RFC 9457 ProblemDetails language, and the full exception detail goes to the log, not to the client. This is one of those changes that takes twenty minutes and saves you on every future debugging session. I go much deeper on mapping custom business exceptions to status codes in Global Error Handling in ASP.NET Core: ProblemDetails Done Right.
Logging with Serilog and configuration per environment
Console.WriteLine debugging dies the moment your API runs on a real server. Serilog gives you structured logs: every entry carries properties you can filter on later, instead of a wall of text you grep and pray over.
We already wired Serilog into Program.cs reading from configuration. That means appsettings.json controls it, and appsettings.Production.json can override it — verbose on your machine, tight on the server:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"WriteTo": [ "Console" ]
}
}The overrides matter. Out of the box, ASP.NET Core and EF Core log at Information level, which buries your own messages under framework noise and generated SQL. In production I keep framework logs at Warning and my application logs at Information, and I add UseSerilogRequestLogging() (already in the pipeline above) so every request produces exactly one clean log line with method, path, status code and elapsed time. When a user reports "the app was slow at 9 PM," that single line format is what lets you answer in minutes instead of guessing.
Add JWT authentication
A catalog anyone can read is fine. A catalog anyone can write to is not. The standard fix is JWT bearer authentication: clients log in once, receive a signed token, and send it with every request.
The minimal wiring in Program.cs (add using System.Text;, using Microsoft.AspNetCore.Authentication.JwtBearer; and using Microsoft.IdentityModel.Tokens; at the top):
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!)),
ClockSkew = TimeSpan.Zero
};
});
builder.Services.AddAuthorization();Then protect the write endpoints with [Authorize] on the POST/PUT/DELETE actions, leaving GETs public. That is genuinely all you need for a first working version — but it is not the version you should ship. Short-lived access tokens, refresh-token rotation, revocation on logout and reuse detection are where real-world JWT setups succeed or fail, and each one has a wrong way to do it that looks right. I cover the complete flow, with all the code, in JWT Authentication in ASP.NET Core 10 With Refresh Tokens — read that before you put authentication in front of real users.
Production checklist: HTTPS, CORS, rate limiting, health checks, Swagger in prod?
Before this API faces the internet, walk this list. Every item is something I have personally seen missing in a "finished" project:
- HTTPS everywhere. Keep
UseHttpsRedirection(), add HSTS in production (app.UseHsts()when not in Development), and terminate TLS at your host or reverse proxy. No exceptions for "internal" APIs that later become public. - CORS configured explicitly. If a browser app consumes your API, define a named policy with the exact origins you trust. Never combine
AllowAnyOrigin()with credentials, and never shipAllowAnyOrigin()because "it made the error go away." We have a whole post on fixing CORS properly if you hit the famous browser error. - Rate limiting on. .NET 10 ships a built-in rate limiter — a fixed-window policy takes a few lines in
Program.cs(AddRateLimiter+UseRateLimiter) and stops the most naive abuse and accidental client loops. - Health checks mapped. Load balancers and container orchestrators need to know whether you are alive.
AddHealthChecks()plusMapHealthChecks("/health")is the baseline; database-aware readiness checks and a status dashboard are covered in Health Checks in ASP.NET Core: Readiness, Liveness and a Status Dashboard. - Secrets out of source control. Connection strings and JWT keys come from environment variables or a secret manager in production. The ones in this tutorial's
appsettings.jsonare for your local machine only. - Swagger/OpenAPI: decide deliberately. .NET 10's built-in OpenAPI (
AddOpenApi()/MapOpenApi()) is great during development. In production, either protect the endpoint behind authentication or turn it off — a public, complete map of your API is a gift to anyone probing it. - Migrations as a release step. Generate the SQL script, review it, run it as part of deployment — not silently at app startup.
Where to go next
You now have an ASP.NET Core 10 Web API with a clean structure, EF Core data access, DTOs, validation, ProblemDetails error handling, structured logging, JWT authentication and a production checklist. That is the foundation every post in this series builds on.
If you only read two follow-ups, make them these: the full JWT authentication guide with refresh tokens to secure the API properly, and the ProblemDetails deep dive to make every error your API returns consistent and debuggable. Build the boring parts correctly once, and every feature after that gets easier.