Middleware is software that's assembled into an application pipeline to handle requests and responses. Each component in the pipeline has the opportunity to process an incoming request, perform operations, and pass control to the next middleware in the sequence. 

Each middleware component is essentially a delegate that can process the HttpContext and optionally invoke the next delegate in the pipeline.

 

Middleware components are executed in the order they are added to the pipeline. Each middleware can:

  • Inspect: Examine the incoming request.
  • Modify: Alter the request or response.
  • Short-circuit: Terminate the request processing early without passing control to the next middleware.
  • Call next: Pass control to the next middleware in the pipeline

 

Custom Middleware Using Delegate

 

 

Registering Above Middleware in the Pipeline

 

 

In Short

  • Delegates: Represent methods with a specific parameter list and return type.
  • Middleware: Components that handle HTTP requests and responses in the request pipeline.
  • RequestDelegate: A delegate type representing methods that process HTTP requests.
  • UseMiddleware(): Adds middleware components to the pipeline.

 

 

 

The execution flow is as follows:

  • Request Processing: Middleware components process the incoming request in the order they are added.
  • Response Processing: After the request has been handled, middleware components process the outgoing response in reverse order

 

 

 

Built-in Middleware Components

ASP.NET Core provides a rich set of built-in middleware components for common tasks:

  • UseStaticFiles() - Serves static files like HTML, CSS, and JavaScript from the wwwroot folder.
  • UseRouting() - Enables routing capabilities for MVC or Razor Pages.
  • UseAuthentication() - Adds authentication support.
  • UseAuthorization() - Adds authorization support.
  • UseEndpoints() - Configures endpoint routing and maps requests to controllers or Razor Pages.
  • UseExceptionHandler() - Provides a global error handling mechanism.
  • UseHttpsRedirection() - Redirects HTTP requests to HTTPS.
  • UseCors() - Configures Cross-Origin Resource Sharing (CORS) policies.

 


Related Question