X

Understand and custom middleware pipeline in ASP.NET Core

Dung Do Tien Aug 23 2020 1075
The middleware in Asp.net Core is a new feature and it is a software component that is assembled into an application pipeline to handle requests and responses.

1. What is middleware in Asp.net core

The middleware is a new feature introduced in Asp.net core, it is very important to process or filter requests and responses to end-users. Middlewares are software components that are assembled into an application pipeline to handle requests and responses. 

You can understand easily middleware looks like a net help filter or process something business code before request or response. You can use middleware to cache page, logging, authentication, cache static file, etc …

To easily imagine the following middleware, you can see the diagram below, which shows the execution of ASP.Net core middleware.

As you can see in the diagram above, the request pipeline consists of a sequence of middleware’s, called one after the other. Each middleware can perform operations before and after it delegates the request or response to the next middleware.

A middleware includes two parts, they are request logic code and response logic code.  it is not required all, it depends on your business. 

Two parts are separated by the next() function, above this function is for request and under is for the response.

To easily understand many middlewares run per request and response. I created two middlewares and started to debug from the beginning of a request to server response to the browser. You can see the image below:

You can see that all request content codes of two middleware are run first and then is response content code.

Asp.net core also provided many middleware build-in available for you such as UseHttpsRedirection(), UseStaticFiles(), UseRouting(), UseCors(), UseAuthentication(), etc ... and you also make a custom middleware for you business.

Middleware will be registered inside the Configure() function of Startup class. So you can open this class to see default some middleware added to your project. They are some required middleware.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    // Middleware help redirect from http to https.
    app.UseHttpsRedirection();

    // Middleware helps enable static file such as image, css, js..
    app.UseStaticFiles();

    // Middleware config route for site.
    app.UseRouting();

    // Middleware enables authentication, by default using Identity.
    app.UseAuthorization();

    // Middleware listen and regist router.
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

2. How to custom middleware in Asp.net core

2.1 Setup environment 

- Visual studio 2017 or 2019

- Asp.Net core 2.2, 3.0 or 3.1

2.2 Create a custom middleware in Asp.net core

I will create a middleware to check permission. If the query string from param url is an administrator will allow display page otherwise it will display denied page.

To create a middleware, In visual studio you can select the folder content middleware and right-click -> select Add.. -> select New Item.. from right dialog you can see search box and press “middleware”.

Select template middleware class, enter name and click Add button.

Okay, now we have a middleware class as below:

namespace MiddlewareExample.Middleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class CustomAuthentication
    {
        private readonly RequestDelegate _next;

        public CustomAuthentication(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {

            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class CustomAuthenticationExtensions
    {
        public static IApplicationBuilder UseCustomAuthentication(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomAuthentication>();
        }
    }
}

We only care about the Invoke() function, we will write the request and response code here.

Okay, now I make an example to filter role login, I will check all Html requests with username query string from URL, if this param is equaled admin or administrator that URL will be pass authentication otherwise I will redirect to the login page. See code below :

public async Task Invoke(HttpContext httpContext)
{
    // START request http code
    var userName = httpContext.Request.Query["username"].ToString();
    if (userName == null) httpContext.Response.Redirect("/home/login");
    if (httpContext.Request.Path != "/home/login")
    {
      if (userName != "admin" && userName != "administrator")
      {
        httpContext.Response.Redirect("/home/login");
      }
    }
    // END request http code

    await _next(httpContext);

    // START response http code
      
    // END response http code
}

This middleware only has request content code, nothing code business for the response.

2.3 Register middleware to configure runtime

To register middleware to configure runtime, open Startup.cs file, inside of Configure() function
We can add middleware here. Don’t forget the order of the middleware is very important. It is only necessary if they depend on each other:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
     …....
     app.UseCustomAuthentication();
    …….
}

Run and see the result :

3. Summary

In this article, I only introduce and guide how to custom middleware in Asp.net Core. I want to note that middleware is an important part of Asp.net core. So I hope this article will help you to understand what is middleware in Asp.net Core? and can create a simple middleware to do something.

You can download source code from GitHub here.