Page Lifecycle
The ASP.NET Core request pipeline processes requests through ordered middleware. Understanding lifecycle hooks enables proper initialization and cleanup.Middleware Order
Middleware order in Program.cs determines execution order:- Exception Handler - Must be first to catch all downstream errors
- HTTPS Redirection - Redirect HTTP to HTTPS
- Static Files - Serve static content before routing
- Routing - Must precede endpoints
- Authentication - Must precede authorization
- Authorization - Must precede endpoints
- Endpoints - MapControllers, MapGet, etc.
Lifecycle Interfaces
IHostedServicehandles startup/background tasks- Minimal APIs bypass controller overhead
IApplicationLifetime.ApplicationStartedfires after host startupApplicationStoppingallows graceful drain of in-flight requests
Model Binding
ASP.NET Core model binding maps HTTP request data (route, query, body, headers) to action method parameters.Binding Sources
- Attributes
- Validation
[FromBody]- JSON body binding[FromRoute]- Route parameter binding[FromQuery]- Query string binding[FromHeader]- HTTP header binding[FromForm]- Form data binding
Key Binding Concepts
[ApiController]attribute enables automatic 400 response on ModelState errors- Validation attributes integrate with ModelState
- Custom model binders implement
IModelBinder - Record types with positional constructors support model binding
[BindNever]excludes a property from bindingIFormFilehandles multipart file uploads
HTTP Methods
HTTP verbs (GET, POST, PUT, PATCH, DELETE) communicate intent in REST APIs. Correct verb usage enables caching, idempotency, and interoperability.HTTP Verb Semantics
Safe Methods
GET - Retrieve without side effects (idempotent)
HEAD - Like GET but no body (existence checks)
Mutating Methods
POST - Create resources (not idempotent)
PUT - Replace entire resources (idempotent)
PATCH - Partial updates
DELETE - Remove resources (idempotent)
Status Code Guidelines
- 200 OK - Successful GET, PUT, PATCH
- 201 Created - Successful POST with Location header
- 204 No Content - Successful DELETE
- 400 Bad Request - Invalid input
- 401 Unauthorized - Authentication required
- 403 Forbidden - Authenticated but unauthorized
- 404 Not Found - Resource doesn’t exist
- 409 Conflict - Concurrency violation
RESTful Principles
REST (Representational State Transfer) defines constraints — statelessness, uniform interface, resource addressability — that make APIs scalable and interoperable.REST Constraints
- Resources are nouns -
/orders/{id}, not/getOrder - Statelessness - Each request carries all context
- Uniform interface - Use HTTP verbs semantically
- Resource representations - Usually JSON
- HATEOAS - Embed links to related/next actions
- Content negotiation - Via Accept header
API Versioning
- URL Path
- Query String
- Header
/api/v1/orders — Most common, explicitAdd API versioning from day one — changing a URI structure after consumers integrate is extremely disruptive and usually impossible.
Routing
ASP.NET Core routing maps incoming URLs to handler endpoints. Route templates define patterns with parameters, constraints, and default values.Route Features
- Route parameters -
{name}syntax; optional with{name?} - Constraints -
{id:int},{slug:alpha},{date:datetime} - Catch-all -
{**path}captures remaining URL segments - Route names - Enable URL generation via
IUrlHelper - MapGroup - Organizes related minimal API routes with shared prefix
Controllers
Controllers in ASP.NET Core MVC and Web API are classes that handle HTTP requests, delegate to services, and return ActionResults.Controller Guidelines
- ControllerBase for APIs; Controller adds View() for MVC
[ApiController]enables automatic 400 on invalid model stateActionResult<T>unifies typed returns with status code resultsProblem()returns RFC 7807-compliant error responses- Route prefix on controller applies to all actions
- Filters apply cross-cutting concerns (auth, logging, validation)
Security (Web)
ASP.NET Core security middleware handles authentication (identity), authorization (permissions), HTTPS enforcement, and CORS policy.Security Layers
- Authentication
- HTTPS & CORS
- JWT Bearer -
AddJwtBearerfor API authentication - Cookie -
AddCookiefor web apps - OAuth2/OIDC - External provider integration
- Certificate - Mutual TLS authentication
Security Best Practices
- Enable HTTPS and HSTS in production
- Use policy-based authorization for complex rules
- Validate JWTs with issuer, audience, and lifetime checks
- Store secrets in Azure Key Vault or environment variables
- Allow specific CORS origins, never wildcard in production
Action Filters
Action filters execute code before and after action method execution. They enable cross-cutting concerns like logging, caching, validation, and exception handling.Filter Types
- Authorization Filters - Run first, enforce access control
- Resource Filters - Run before model binding, good for caching
- Action Filters - Run before/after action execution
- Result Filters - Run before/after result execution
- Exception Filters - Handle unhandled exceptions
Filter Features
FilterContextprovides access to route, model state, and result[ServiceFilter]and[TypeFilter]enable DI inside filters- Short-circuiting: set
context.Resultto skip action - Global filters:
AddControllers(o => o.Filters.Add(...))
Use result filters for response transformation (adding headers, wrapping in envelope) rather than doing it in each action method.
Logging
Track request timing and parameters
Caching
Short-circuit with cached responses
Validation
Enforce business rules globally