In this article, I will learn about Middleware and ordring of middleware in .Net Core.
Middleware in .NET Core is a software component that is executed as part of the request and response pipeline in a web application. It acts as an intermediary between a request and the eventual handling of that request by the application. Middleware processes incoming HTTP requests before they reach a controller or an endpoint and can also process outgoing HTTP responses before they are sent back to the client.
Middleware can be used for various purposes, including request filtering. It can filter requests based on various criteria. E.g. you might have middleware that checks whether a user is authenticated before allowing access to certain URLs or routes. By examining these attributes of incoming requests, middleware can decide whether to allow, reject, modify, or redirect them before passing them on to the main application logic.
Each middleware component in the pipeline can either.
Middleware provides several advantages for handling HTTP requests and responses in a modular, layered approach:
Middleware components are executed in the order they are added in the pipeline, and the response flows back in the reverse order. Each middleware executes sequentially, collectively handling incoming requests in the specified order.
Middleware configuration and other application setup tasks were combined into the Program.cs file for improved organization and clarity.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage(); // 1: Handles exceptions first
}
app.UseStaticFiles(); // 2: Serves static files (CSS, JS, images)
app.UseRouting(); // 3: Matches incoming request to endpoints (routes)
app.UseAuthentication(); // 4: Authenticates the user
app.UseAuthorization(); // 5: Authorizes the user to access certain resources
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // 6: Executes the actual controller actions
});
}
Middleware can choose to either pass control to the next middleware or short-circuit the pipeline. For example, if authentication fails, the authentication middleware might return a 401 response and prevent further middleware from being executed.
public async Task InvokeAsync(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
return; // Short-circuit the pipeline
}
await _next(context); // Pass to the next middleware
}
The following are the examples of middleware.