BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News ASP.NET Core Provides Modularity with Middleware Components

ASP.NET Core Provides Modularity with Middleware Components

This item in japanese

ASP.NET Core introduces middleware as a concept to customize the HTTP pipeline. Middleware are components which are composed together to form a web application. The concept was inspired by OWIN and Katana, which provided similar functionalities in earlier versions of ASP.NET.

A middleware is a component sitting on the HTTP pipeline. Middleware are executed one by one, with the responsability to execute the next middleware in the pipeline. Each middleware may terminate the call chain. For example, the authentication middleware would not execute the next middleware if the authentication process failed. The following image illutrates the execution flow.

Aside from the pre-built middleware included in ASP.NET Core, it is also possible to create new ones. A custom middleware is defined by a class with a method accepting an HttpContext as its first parameter. The method may include additional parameters, which will be resolved by dependency injection. The following class defines a logging middleware:

public class RequestLoggerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation("Handling request: " + context.Request.Path);
        await _next.Invoke(context);
        _logger.LogInformation("Finished handling request.");
    }
}

The middleware, in order to be executed, must be registered in the Configure method of the Startup class.

  public void Configure(IApplicationBuilder app)
  {
      app.UseMiddleware<RequestLoggerMiddleware>();
  }

An important point to note is that middleware are executed in the order they are added to the pipeline. This means some care must be put into determining the implicit dependencies between middleware. For example, a component using session state but executed before the session middleware would result in a crash.

With the “pay for what you use” philosophy of ASP.NET Core, some applications may benefit from improved performance as only middleware configured explicitly will run. The framework is no longer based on System.Web.dll; components are instead available as NuGet packages. This also means updates are now handled by NuGet, providing the ability to update each middleware separately.

Rate this Article

Adoption
Style

BT