skip to content
Mohammad Rebati

Explore ASP.NET Core's middleware, routing, and endpoints.

/ 2 min read

Middleware in ASP.NET Core

Middleware components are crucial in the ASP.NET Core request pipeline, where they handle requests and responses. Each middleware can:

  • Process the request and optionally pass it on to the next middleware.
  • Perform actions both before and after the next middleware in the pipeline.

Common middleware include:

  • Authentication Middleware: Validates user identities.
  • Routing Middleware: Determines which route the request matches.
  • Static Files Middleware: Handles requests for static files and terminates the pipeline if a file is served.

Routing and Endpoints

Routing in ASP.NET Core maps incoming requests to endpoints based on the requested URL and other request data. This is managed by the UseRouting middleware, which is typically followed by UseAuthorization and then UseEndpoints. Here is a typical setup:

app.UseEndpoints(endpoints =>
endpoints.MapControllers(); // For attribute-routed controllers
endpoints.MapRazorPages(); // For Razor Pages

Middleware Positioning and Lifecycle

The order in which middleware are configured in the pipeline is vital:

  1. Before UseRouting:
  • These middleware run before the routing decision is made.
  • Suitable for logging, error handling, or culture-specific configurations.
  1. Between UseRouting and UseEndpoints:
  • Runs after the route is known but before the endpoint execution.
  • This is the typical place for UseAuthentication and UseAuthorization.
  1. After UseEndpoints:
  • Usually executes if no endpoint is matched.
  • Useful for handling 404 errors or serving a default response.

Adding Middleware Inside UseEndpoints

Injecting middleware directly inside UseEndpoints is unconventional. This method is reserved for mapping endpoints rather than inserting additional middleware behaviors. However, you can simulate middleware-like functionality inside endpoint definitions using local functions or specific middleware for particular routes.

Lifecycle Overview

  • Startup: Middleware is configured in the Program.cs file.
  • Request Handling:
    • The pipeline starts with the first middleware and continues unless short-circuited.
    • UseRouting decides the appropriate endpoint.
    • Middleware between UseRouting and UseEndpoints may execute based on conditions like authorization.
    • The selected endpoint processes the request.
  • Response: The response is constructed and returned, potentially passing back through middleware that can modify the response.

This structure allows ASP.NET Core applications to be highly adaptable and efficient, ensuring robust handling of requests and streamlined processing.