ASP.NET Core
ASP.NET Core is the cross-platform .NET framework for HTTP APIs, server-rendered applications, real-time systems, background-enabled web services, and cloud-native workloads.
Overview
An ASP.NET Core application is a hosted process with configuration, logging, dependency injection, and an ordered HTTP middleware pipeline. Kestrel accepts a request, middleware applies cross-cutting behavior, routing selects an endpoint, and the endpoint coordinates application services before the response travels back through the pipeline. The framework supplies primitives for authentication, authorization, validation, problem details, rate limiting, caching, health checks, graceful shutdown, and telemetry, but teams must still choose clear boundaries and verify the complete runtime path.
What you will learn
- Explain how Kestrel, middleware, routing, endpoints, dependency injection, and application services collaborate for one HTTP request.
- Build a small API that returns consistent success and problem-detail responses.
- Place exception handling, correlation, rate limiting, and endpoint execution in an intentional order.
- Separate liveness from readiness and propagate request cancellation to downstream work.
- Verify routing, serialization, validation, middleware, and headers through end-to-end tests.
Prerequisites
- Comfort with C# types, records, asynchronous methods, and cancellation tokens.
- The .NET 10 SDK and an editor or terminal capable of sending HTTP requests.
- Basic HTTP knowledge: methods, routes, headers, status codes, and JSON bodies.
When to use ASP.NET Core
Good fit
- HTTP APIs, web applications, real-time hubs, backend-for-frontend services, and cloud-hosted .NET workloads.
- Systems that benefit from built-in dependency injection, configuration, logging, security middleware, health checks, and test hosting.
- Teams that want one programming model from a small minimal API to a structured controller-based application.
Choose another approach when
- A simple scheduled or queue-driven process with no HTTP surface; use a Worker Service instead.
- Static content that can be served directly from object storage or a CDN without an application process.
- A requirement to hide unclear domain boundaries inside controllers or endpoint handlers; design the application model first.
Key concepts
WebApplication composes configuration, logging, services, server startup, and lifetime while Kestrel accepts HTTP connections.
Ordered components can inspect, enrich, reject, short-circuit, or pass requests to the next component and then observe the response.
Endpoint routing matches method, path, constraints, and metadata to minimal API handlers, controllers, Razor pages, hubs, or health checks.
The built-in container creates endpoint and service dependencies with singleton, scoped, or transient ownership.
Status codes, headers, JSON shapes, validation responses, and problem details form the observable contract clients depend on.
Exception handling, authentication, authorization, rate limiting, caching, health checks, and telemetry belong in the runtime design, not as afterthoughts.
Architecture
A request enters Kestrel, receives cross-cutting policy in middleware, is matched by routing, reaches a feature endpoint, and coordinates an application boundary before the response returns through the same pipeline.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01Create the host
Use WebApplication.CreateBuilder to load configuration, logging, environment information, and the dependency-injection container.
- 02Register capabilities
Add problem details, repositories, health checks, rate limiting, options, and other dependencies before building the application.
- 03Compose middleware
Order exception handling, correlation, security, rate limiting, caching, and routing based on which requests and responses each component must observe.
- 04Map feature endpoints
Group related routes, attach metadata and policies, validate boundary input, call application services, and translate outcomes into HTTP responses.
- 05Propagate cancellation
Pass the request CancellationToken into database, messaging, and outbound HTTP work so disconnected requests do not waste resources.
- 06Expose health signals
Keep liveness focused on the process and readiness focused on dependencies required to serve traffic.
- 07Test through HTTP
Use WebApplicationFactory to exercise the real middleware, routing, serialization, validation, and response contract.
Code example
The dedicated sample keeps startup readable while registering problem details, health checks, rate limiting, correlation, and a feature-oriented product endpoint group.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddSingleton<IProductRepository, InMemoryProductRepository>();
builder.Services.AddHealthChecks();
builder.Services.AddRateLimiter(options =>
options.AddFixedWindowLimiter("api", limiter =>
{
limiter.PermitLimit = 20;
limiter.Window = TimeSpan.FromMinutes(1);
}));
var app = builder.Build();
app.UseExceptionHandler();
app.UseMiddleware<CorrelationIdMiddleware>();
app.UseRateLimiter();
app.MapProductEndpoints();
app.MapHealthChecks("/health/live");
app.MapHealthChecks("/health/ready");
app.Run();Testing strategy
Unit tests are useful for domain rules, but an HTTP application also needs integration tests that prove framework configuration works together.
- Create the application with WebApplicationFactory so tests use the real service registrations and middleware pipeline.
- Test successful and failed routes, JSON serialization, validation problem details, headers, and status codes.
- Avoid assertions that depend on test execution order or shared mutable state.
- Keep live external-service tests behind an explicit opt-in flag; normal tests should remain deterministic.
Security considerations
Security depends on middleware order, endpoint metadata, trusted proxy configuration, and safe boundary handling.
- Authenticate before authorization and require policies on route groups or endpoints instead of relying on UI visibility.
- Validate and normalize all boundary input; never bind persistence entities directly as public contracts.
- Configure forwarded headers only for known proxies and do not trust arbitrary client identity headers.
- Limit request sizes, protect secrets with environment-specific providers, and return safe problem details without stack traces.
Performance and scalability
ASP.NET Core is efficient by default, but application throughput is usually constrained by blocking I/O, unbounded work, serialization, databases, or downstream services.
- Use asynchronous APIs for I/O and pass cancellation tokens throughout the call chain.
- Bound request bodies, query results, queues, concurrency, retries, and outbound timeouts.
- Measure with metrics and traces before optimizing allocations or switching serializers.
- Use output caching only for responses whose identity, authorization, and invalidation rules are explicit.
Deployment and operations
A deployable API needs more than a successful local build.
- Publish for the target OS and architecture, run containers as non-root, and scan dependencies and images in CI.
- Terminate TLS at a trusted boundary and configure reverse-proxy headers, host filtering, and HTTPS behavior consistently.
- Export structured logs, metrics, and traces with correlation across inbound and outbound calls.
- Handle graceful shutdown, readiness changes, configuration validation, and database migrations as deliberate operational workflows.
Common problems and fixes
An endpoint always returns 404.
Likely cause: The route, HTTP method, constraint, base path, or endpoint registration does not match the request.
Fix: Inspect the mapped endpoint pattern and test the exact URL and method through WebApplicationFactory or an HTTP file.
Requests return 401 or 403 unexpectedly.
Likely cause: Authentication did not establish an identity, a policy requirement failed, or middleware is ordered incorrectly.
Fix: Separate authentication from authorization, inspect claims, and integration-test the endpoint metadata and middleware order.
The application hangs under load.
Likely cause: Blocking calls, missing timeouts, unbounded concurrency, thread-pool starvation, or a slow downstream dependency is consuming request capacity.
Fix: Capture traces and runtime metrics, remove sync-over-async calls, add timeouts and bounds, and load-test the real dependency path.
The service is healthy but cannot serve traffic.
Likely cause: A single health endpoint reports process health without checking required dependencies.
Fix: Use separate liveness and readiness checks and make readiness fail when a required dependency is unavailable.
Best practices
- Keep the composition root readable and registrations close to their feature boundaries.
- Keep middleware order explicit and cover security-sensitive ordering with integration tests.
- Return consistent problem details for failures instead of ad hoc error shapes.
- Propagate request cancellation to database and outbound HTTP operations.
- Expose separate liveness and readiness checks when orchestration depends on them.
- Keep business rules outside HttpContext-dependent code so they remain fast to test.
Production checklist
- Configuration is validated on startup and secrets are not stored in source control.
- Authentication, authorization, CORS, forwarded headers, and rate limits match the deployment boundary.
- Errors use safe problem details and logs contain correlation without sensitive payloads.
- Liveness and readiness have distinct meanings and are tested during dependency failure.
- Outbound calls have timeouts, resilience policies, cancellation, and telemetry.
- Integration tests cover critical routes and the published artifact is smoke-tested in CI.
Common interview questions
Why does middleware order matter?
Each middleware wraps the next component. Ordering changes which requests it sees and whether authentication, authorization, exceptions, and endpoints behave correctly.
What is Kestrel?
Kestrel is ASP.NET Core's cross-platform web server. It can be internet-facing or run behind a reverse proxy depending on the deployment.
When would you choose controllers over minimal APIs?
Controllers are useful when conventions, filters, model-binding customization, and a structured large API surface outweigh minimal APIs' compact vertical-slice style.
What is the difference between liveness and readiness?
Liveness answers whether the process should be restarted. Readiness answers whether this instance currently has the dependencies and state required to receive traffic.
Why use WebApplicationFactory instead of testing handlers directly?
Handler tests do not prove route matching, middleware order, dependency registration, serialization, filters, or headers. WebApplicationFactory exercises those behaviors through the in-memory HTTP server.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
ASP.NET Core Product API
A focused .NET 10 API demonstrating middleware ordering, dependency injection, validation problem details, rate limiting, health checks, correlation IDs, HTTP requests, Docker, and end-to-end tests.
- Run
dotnet run --project src/AspNetCoreApi.Api- Test
dotnet test AspNetCoreApi.slnx