Middleware in .NetCore


In this article, I will learn about Middleware and ordring of middleware in .Net Core.

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.

  • Modify the incoming request (e.g., logging, authentication).
  • Pass control to the next middleware.
  • Terminate the request without passing it to the next middleware.

Why Use Middleware?

Middleware provides several advantages for handling HTTP requests and responses in a modular, layered approach:

  1. Separation of Concerns - Middleware allows you to separate different parts of request processing, such as authentication, authorization, logging, error handling, etc.
  2. Modular and Composable - Middleware components can be composed to form a pipeline, and you can add or remove middleware as needed to control how requests are handled.
  3. Control over Request Lifecycle - Middleware gives fine-grained control over how requests are processed, allowing for filtering, modifying, or even terminating requests before they reach the core application logic.
  4. Performance Optimization - By using middleware efficiently, certain tasks can be completed at early stages of the request pipeline, reducing the load on the later stages.
  5. Reusability - Middleware components can be reused across different applications or projects. For example, you can create middleware for logging, error handling, or security and reuse them in multiple projects.

Ordering of Middleware

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 in .NetCore

Program.cs file Middleware Ordering

Middleware configuration and other application setup tasks were combined into the Program.cs file for improved organization and clarity.

Middleware in .NetCore
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
    });
}
  1. UseDeveloperExceptionPage() - This should be first (in development) to handle any exceptions in the pipeline and return detailed error information.
  2. UseStaticFiles() - Static files should be served early, so the request doesn’t go through unnecessary middleware for static file requests.
  3. UseRouting() - This sets up route matching for controllers or Razor Pages.
  4. UseAuthentication() - Authentication needs to occur before authorization so that the system knows who the user is.
  5. UseAuthorization() - Authorization ensures the authenticated user has the necessary permissions to access the resource.
  6. MapControllers() - This is where the actual business logic in your controller actions executes.

Short-circuiting Middleware

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
}

Real-World Examples

The following are the examples of middleware.

  1. Authentication
  2. Authorization
  3. Logging
  4. Error Handling,
  5. Static File Serving
  6. CORS
  7. Compression

Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question