ASP.NET Core is the framework for building web applications and APIs in C#. It is cross-platform, fast, and built around dependency injection and a middleware pipeline. This guide covers both ways of writing endpoints, how a request actually travels through the application, and the configuration you need before deploying.
Getting started#
dotnet new webapi -n MyApi
cd MyApi
dotnet run
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ShopContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
app.MapGet("/products", async (IProductService service) =>
Results.Ok(await service.ListAsync()));
app.Run();
Two phases, and the split matters. Before Build() you register services; after it you configure the pipeline and endpoints. Trying to register a service after building throws.
Minimal APIs#
app.MapGet("/products/{id:int}", async (int id, IProductService service) =>
{
var product = await service.FindAsync(id);
return product is null ? Results.NotFound() : Results.Ok(product);
});
app.MapPost("/products", async (ProductRequest request, IProductService service) =>
{
var created = await service.CreateAsync(request);
return Results.Created($"/products/{created.Id}", created);
});
app.MapDelete("/products/{id:int}", async (int id, IProductService service) =>
{
await service.DeleteAsync(id);
return Results.NoContent();
});
Parameters are bound automatically: route values by name, services from the container, and a complex type from the JSON body. The :int constraint means a non-numeric id gets a 404 rather than reaching your code.
Group related endpoints to avoid repeating the prefix and the shared configuration:
var products = app.MapGroup("/api/products").RequireAuthorization();
products.MapGet("/", GetAll);
products.MapGet("/{id:int}", GetOne);
products.MapPost("/", Create);
Controllers#
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _service;
public ProductsController(IProductService service) => _service = service;
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> Get(
[FromQuery] int page = 1, CancellationToken ct = default)
{
return Ok(await _service.ListAsync(page, ct));
}
[HttpGet("{id:int}")]
public async Task<ActionResult<Product>> Get(int id, CancellationToken ct)
{
var product = await _service.FindAsync(id, ct);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
public async Task<ActionResult<Product>> Create(
ProductRequest request, CancellationToken ct)
{
var created = await _service.CreateAsync(request, ct);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}
}
[ApiController] does several useful things automatically: model validation before your method runs, binding a complex parameter from the body without an attribute, and returning a standard problem-details response for validation failures.
| Minimal APIs | Controllers |
|---|---|
| Less ceremony | Familiar structure for larger teams |
| Slightly faster | Filters and model binding conventions |
| Good for small services | Good for large applications |
Dependency injection#
builder.Services.AddSingleton<IClock, SystemClock>(); // one per application
builder.Services.AddScoped<IProductService, ProductService>(); // one per request
builder.Services.AddTransient<IEmailSender, SmtpSender>(); // one per injection
builder.Services.AddHttpClient<IPaymentClient, PaymentClient>(client =>
{
client.BaseAddress = new Uri("https://api.payments.example");
client.Timeout = TimeSpan.FromSeconds(10);
});
AddHttpClient matters more than it looks. Creating an HttpClient per request exhausts sockets under load; the factory manages the underlying connections correctly.
The middleware pipeline#
app.UseExceptionHandler("/error");
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Each request passes down this list and the response passes back up. Order is behaviour, not style:
- Exception handling first, so it can catch everything below it.
- Authentication before authorisation — you cannot check permissions before establishing identity.
- Static files early, so an image request does not run the whole pipeline.
- Endpoints last.
Writing your own is straightforward:
app.Use(async (context, next) =>
{
var stopwatch = Stopwatch.StartNew();
await next();
logger.LogInformation("{Method} {Path} took {Ms}ms",
context.Request.Method, context.Request.Path, stopwatch.ElapsedMilliseconds);
});
Calling next() continues the pipeline; not calling it short-circuits the request, which is how authentication middleware returns a 401.
Validation#
public record ProductRequest(
[Required, StringLength(120)] string Name,
[Range(0.01, 100000)] decimal Price);
With [ApiController], a failure returns a 400 with a structured body before your method runs. For anything beyond attributes, FluentValidation gives you real conditional rules:
public class ProductValidator : AbstractValidator<ProductRequest>
{
public ProductValidator(IProductRepository repo)
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(120)
.MustAsync(async (name, ct) => !await repo.ExistsAsync(name, ct))
.WithMessage("A product with that name already exists");
RuleFor(x => x.Price).GreaterThan(0);
}
}
Error handling#
app.UseExceptionHandler(handler =>
{
handler.Run(async context =>
{
var feature = context.Features.Get<IExceptionHandlerFeature>();
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
logger.LogError(feature?.Error, "Unhandled exception");
context.Response.StatusCode = feature?.Error switch
{
NotFoundException => StatusCodes.Status404NotFound,
ValidationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError,
};
await context.Response.WriteAsJsonAsync(new
{
error = context.Response.StatusCode == 500
? "An unexpected error occurred"
: feature?.Error.Message,
});
});
});
Log the real exception, return something generic for a 500. An exception message can contain table names, file paths and occasionally credentials.
Configuration#
{
"ConnectionStrings": { "Default": "Server=localhost;Database=shop;" },
"Email": { "Host": "smtp.example.com", "Port": 587 },
"Logging": { "LogLevel": { "Default": "Information" } }
}
builder.Services.Configure<EmailOptions>(
builder.Configuration.GetSection("Email"));
public class EmailSender
{
private readonly EmailOptions _options;
public EmailSender(IOptions<EmailOptions> options) => _options = options.Value;
}
Sources layer, later winning: appsettings, then the environment-specific file, then environment variables, then command-line arguments. Secrets belong in dotnet user-secrets locally and environment variables or a vault in production.
Before production#
- Detailed error pages off — check
app.Environment.IsDevelopment() - HTTPS redirection and HSTS enabled
- A health endpoint:
app.MapHealthChecks("/health") - Structured logging going somewhere you can search
- Rate limiting on public endpoints
- CORS listing the origins you actually allow, not a wildcard with credentials
- Secrets from the environment, never from source control
app.UseRateLimiter();
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("api", limiter =>
{
limiter.PermitLimit = 100;
limiter.Window = TimeSpan.FromMinutes(1);
});
});
Questions people ask#
Minimal APIs or controllers?
Minimal APIs for small services and microservices. Controllers when you have many endpoints, filters and conventions to share, or a team that expects the structure. Performance is close enough not to decide it.
Does ASP.NET Core run on Linux?
Yes, fully, and it is the common deployment target. Kestrel is the built-in server, usually behind nginx or a cloud load balancer.
Why does my API return 415?
Unsupported media type — the request is missing Content-Type: application/json, so the body cannot be bound.
How do I document the API?
The template includes OpenAPI support, which generates a machine-readable description. Add Swagger UI or Scalar on top for a browsable page during development.
Where to go next#
- C# and databases — the data layer behind these endpoints.
- C# security — what to get right before going live.
- C# deployment — publishing and hosting.