Skip to content

ASP.NET Core Web API: controllers, routing, pipeline

ASP.NET Core Web API is the part of ASP.NET Core used to build HTTP services: public REST APIs, internal service-to-service endpoints, and backends for single-page and mobile apps. It runs on every platform .NET supports, is hosted by the Kestrel web server, and shares dependency injection, configuration and logging with the rest of .NET.

A request travels through three layers. Middleware handles cross-cutting work (errors, HTTPS, CORS, authentication). Routing picks the endpoint whose template matches the URL and HTTP method. The endpoint (a controller action or a Minimal API handler) binds the request to parameters, calls your services and returns a result. This page walks through that path with one OrdersPortal API.

The samples are file-based programs for the .NET 10 SDK. Start one with dotnet run file.cs --urls http://127.0.0.1:5126 and call it with curl. They were run with .NET SDK 10.0.115.

Topic What it covers
Controllers and routing [ApiController], attribute routes, route constraints, model binding, automatic validation, ActionResult<T> and CreatedAtRoute.
Middleware and pipeline The order an API pipeline needs, problem details, IExceptionHandler and CORS.
Choosing between them Controllers or Minimal APIs, and where logic belongs.

A controller is a class deriving from ControllerBase whose public methods (actions) handle requests. builder.Services.AddControllers() registers MVC services and app.MapControllers() adds an endpoint for each action. The [ApiController] attribute switches on API conventions: attribute routing is required, binding sources are inferred (complex types from the body, simple types from the route or query), and an invalid model state returns a 400 problem details response automatically, before your action runs.

Routes come from attributes. [Route("api/customers/{customerId:int}/orders")] on the class sets a prefix, and [HttpGet("{orderId:int}")] on an action adds to it. Constraints such as :int, :guid or :min(1) decide whether a route matches; they are not input validation, so a non-matching value gives 404, not 400. Design routes around resources (nouns, plural, nested only for real ownership) and let the HTTP method carry the verb: GET reads, POST creates, PUT replaces, PATCH updates part, DELETE removes.

Return ActionResult<T>: the action can return a T (serialized with 200) or a status result such as NotFound(). For creation, CreatedAtRoute returns 201 with a Location header that points at the new resource. Map entities to DTOs at this boundary so internal fields never leave the service; see Entities vs DTOs.

#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddControllers();
builder.Services.AddSingleton<OrderRepository>();
var app = builder.Build();
app.MapControllers();
app.Run();
[ApiController]
[Route("api/customers/{customerId:int}/orders")]
public class CustomerOrdersController(OrderRepository repository) : ControllerBase
{
// GET api/customers/7/orders?status=Pending
[HttpGet]
public ActionResult<IEnumerable<OrderDto>> List(int customerId, [FromQuery] string? status) =>
Ok(repository.ForCustomer(customerId)
.Where(o => status is null || o.Status == status)
.Select(OrderDto.From));
// GET api/customers/7/orders/1001
[HttpGet("{orderId:int}", Name = nameof(GetById))]
public ActionResult<OrderDto> GetById(int customerId, int orderId) =>
repository.Find(customerId, orderId) is { } order ? OrderDto.From(order) : NotFound();
// POST api/customers/7/orders
[HttpPost]
public ActionResult<OrderDto> Create(int customerId, CreateOrderRequest request)
{
var order = repository.Add(customerId, request.Sku, request.Quantity);
return CreatedAtRoute(nameof(GetById), new { customerId, orderId = order.Id }, OrderDto.From(order));
}
}
public record CreateOrderRequest([Required] string Sku, [Range(1, 100)] int Quantity);
public record OrderDto(int Id, string Sku, int Quantity, string Status)
{
public static OrderDto From(Order o) => new(o.Id, o.Sku, o.Quantity, o.Status);
}
public class Order
{
public int Id { get; init; }
public int CustomerId { get; init; }
public required string Sku { get; init; }
public int Quantity { get; init; }
public string Status { get; set; } = "Pending";
public string InternalNotes { get; set; } = ""; // never leaves the API: the DTO omits it
}
// In-memory store for the sample only; it is not thread-safe.
public class OrderRepository
{
private readonly List<Order> _orders =
[
new() { Id = 1001, CustomerId = 7, Sku = "KB-101", Quantity = 2, Status = "Shipped" },
];
public IEnumerable<Order> ForCustomer(int customerId) => _orders.Where(o => o.CustomerId == customerId);
public Order? Find(int customerId, int id) => _orders.FirstOrDefault(o => o.CustomerId == customerId && o.Id == id);
public Order Add(int customerId, string sku, int quantity)
{
var order = new Order { Id = _orders.Max(o => o.Id) + 1, CustomerId = customerId, Sku = sku, Quantity = quantity };
_orders.Add(order);
return order;
}
}

Calls and responses (traceId values differ per run):

$ curl -i -X POST http://127.0.0.1:5126/api/customers/7/orders -H "Content-Type: application/json" -d '{"sku":"MS-220","quantity":1}'
HTTP/1.1 201 Created
Location: http://127.0.0.1:5126/api/customers/7/orders/1002
{"id":1002,"sku":"MS-220","quantity":1,"status":"Pending"}
$ curl "http://127.0.0.1:5126/api/customers/7/orders?status=Pending"
[{"id":1002,"sku":"MS-220","quantity":1,"status":"Pending"}]
$ curl -X POST http://127.0.0.1:5126/api/customers/7/orders -H "Content-Type: application/json" -d '{"quantity":500}'
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"Sku":["The Sku field is required."],"Quantity":["The field Quantity must be between 1 and 100."]},"traceId":"..."}
$ curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:5126/api/customers/7/orders/9999
404
$ curl -o /dev/null -w "%{http_code}\n" http://127.0.0.1:5126/api/customers/abc/orders
404

Pitfalls:

  • Fat controllers. Actions should translate HTTP to a service call and back. Business rules in actions cannot be reused by a background job or tested without HTTP.
  • Returning entities. Serializing EF Core entities leaks internal columns, couples the public contract to the database schema and can trigger lazy-loading cycles. Return DTOs.
  • Route constraints as validation. {id:int} turns abc into a 404. Validate business rules (ranges, formats) with validation attributes or in the service so callers get a 400 that explains the problem.

Before any action runs, the request passes through the middleware registered in Program.cs, in registration order; the response travels back in reverse. For an API the usual order is: exception handling, HSTS and HTTPS redirection, CORS, authentication, authorization, then your own middleware such as rate limiting or request logging, then the endpoints (routing is added automatically by WebApplication). The general mechanics of Use, Run and Map are covered on .NET core features; this section focuses on what an API needs.

Errors deserve the most care. Clients should get a consistent, machine-readable body for every failure: ASP.NET Core implements problem details (RFC 9457, which replaced RFC 7807). AddProblemDetails() plus UseExceptionHandler() turns unhandled exceptions into a 500 problem details response without leaking stack traces, and UseStatusCodePages() gives empty 4xx responses (for example a bare NotFound() from a Minimal API) the same shape. Since .NET 8, IExceptionHandler lets you map known exceptions to specific status codes in one place instead of try/catch in every action. CORS must come before authentication and authorization so browser preflight OPTIONS requests get an answer.

#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<OrderConflictHandler>();
builder.Services.AddCors(o => o.AddPolicy("portal", p => p.WithOrigins("https://portal.example.test").AllowAnyHeader()));
var app = builder.Build();
app.UseExceptionHandler(); // 1. catches everything below it
app.UseStatusCodePages(); // 2. empty 4xx/5xx responses get a problem details body
app.UseCors("portal"); // 3. before auth so preflight requests are answered
// app.UseAuthentication(); // 4. who is calling (needs a configured scheme)
// app.UseAuthorization(); // 5. may they call this endpoint
app.MapPost("/api/orders/{id:int}/cancel", (int id) =>
{
if (id == 1001) throw new OrderConflictException(id, "Shipped");
return Results.NoContent();
});
app.MapGet("/api/orders/{id:int}", (int id) => Results.NotFound());
app.Run();
public sealed class OrderConflictException(int orderId, string status)
: Exception($"Order {orderId} is {status} and can no longer be cancelled.");
public sealed class OrderConflictHandler(IProblemDetailsService problemDetails) : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
{
if (exception is not OrderConflictException) return false; // let the default handler deal with it
context.Response.StatusCode = StatusCodes.Status409Conflict;
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = context,
ProblemDetails = new ProblemDetails
{
Title = "Order cannot be cancelled",
Detail = exception.Message,
Status = StatusCodes.Status409Conflict,
},
});
}
}

Calls and responses:

$ curl -i -X POST http://127.0.0.1:5127/api/orders/1001/cancel
HTTP/1.1 409 Conflict
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.10","title":"Order cannot be cancelled","status":409,"detail":"Order 1001 is Shipped and can no longer be cancelled.","traceId":"..."}
$ curl -o /dev/null -w "%{http_code}\n" -X POST http://127.0.0.1:5127/api/orders/1002/cancel
204
$ curl http://127.0.0.1:5127/api/orders/5
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Not Found","status":404,"traceId":"..."}
$ curl -i -X OPTIONS http://127.0.0.1:5127/api/orders/5 -H "Origin: https://portal.example.test" -H "Access-Control-Request-Method: GET"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://portal.example.test

Pitfalls:

  • The developer exception page in production. It shows stack traces and configuration. WebApplication enables it only in Development; never force it on elsewhere.
  • AllowAnyOrigin with credentials. Browsers reject that combination, and allowing every origin on an authenticated API is a security hole. List the real origins.
  • Exceptions for control flow. IExceptionHandler is for unexpected or cross-cutting failures. Expected outcomes such as “not found” are cheaper and clearer as return values (NotFound(), TypedResults.Conflict()).

ASP.NET Core offers two ways to write the endpoint itself, and both run on the same routing and middleware.

Controllers Minimal APIs
Shape Classes with action methods and attributes Lambdas or methods mapped with MapGet/MapPost
Validation Automatic with [ApiController] AddValidation() (.NET 10)
Cross-cutting MVC filters, conventions, application model Endpoint filters, route groups
Native AOT Not supported Supported
Best for Large existing APIs, teams used to MVC, heavy filter use New services, small and medium APIs, AOT and serverless

Whichever you choose, keep the layering the same: middleware for cross-cutting concerns, thin endpoints that translate HTTP, services for business rules, repositories or EF Core for data, and DTOs at the boundary. The Minimal APIs section shows the same OrdersPortal endpoints in the Minimal API style.

What does [ApiController] change? It requires attribute routing, infers binding sources ([FromBody] for complex types, route or query for simple ones), returns a 400 problem details response automatically when model validation fails, and uses problem details for error status codes.

What is the difference between a route constraint and validation? A constraint decides whether a route matches at all; a failed constraint means “no endpoint”, so the client gets 404. Validation runs after binding on a matched endpoint and returns 400 with field errors. Use constraints only to disambiguate routes.

Why return 201 with a Location header from a POST? HTTP semantics: 201 says a resource was created and Location tells the client its URL, so it does not need to construct it. CreatedAtRoute and CreatedAtAction build the URL from the route table, so it stays correct when routes change.

How would you return consistent errors from an API? Use problem details everywhere: AddProblemDetails, UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty error responses, IExceptionHandler to map known domain exceptions to status codes, and validation responses from [ApiController] or AddValidation.

Senior scenario: a public OrdersPortal API needs a breaking change to the order contract. How do you ship it? Do not change the existing contract in place. Introduce a new version (URL segment such as /api/v2/orders or a header, using the Asp.Versioning packages), keep v1 running and mapping from the same domain model through its own DTOs, document both in OpenAPI, announce a deprecation date with a Sunset or deprecation header, monitor v1 traffic, and remove it only when usage reaches zero or the date passes.