Order of Middleware Pipeline in Asp.net Core

Order of Middleware Pipeline in Asp.net Core
1. Exception/Error Handling:
Purpose: Catches and handles exceptions that occur anywhere in the pipeline.
Examples: UseExceptionHandler, UseDeveloperExceptionPage (for development environments).
2. HTTPS Redirection:
Purpose: Redirects HTTP requests to HTTPS for security.
Example: UseHttpsRedirection.
3. Static Files:
Purpose: Serves static files like images, CSS, and JavaScript directly to the client.
Example: UseStaticFiles.
4. Routing:
Purpose: Matches incoming requests to specific endpoints based on their URLs.
Examples: UseRouting, UseEndpoints.
5. CORS (Cross-Origin Resource Sharing):
Purpose: Enables secure cross-origin requests from different domains.
Example: UseCors.
6. Authentication:
Purpose: Verifies user identities and establishes a user principal.
Example: UseAuthentication.
7. Authorization:
Purpose: Determines whether a user is allowed to access a particular resource or perform a certain action.
Example: UseAuthorization.
8. Custom Middleware:
Purpose: Your application-specific middleware components to handle tasks like logging, feature flags, etc.

Example (Program.cs or Startup.cs):
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
 
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
 
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
 
// … your custom middleware …
 
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers(); // Or MapRazorPages(), MapGet(), etc.
});

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply