How to customize Middleware in asp.net core

Time:2021-8-15

Asp.net core is a cross platform, open source, lightweight, high-performance and highly modular web framework with strong scalability. You canrequest -> responseIn this article, we will discuss the asp.net core middleware and how to use it.

One exists in asp.net coremiddleware Chain, this chain is made of a set ofDelegation methodThese delegate methods will be executed one by one, and the request will flow from these middleware chains. The components transferred to either process the request or pass the request to the next middleware.

Configure middleware pipeline

The pipeline configuration of middleware is in the startup. Configure method. To be exact, this is to assemble your ASP. Net core request pipeline. ASP. Net runtime will automatically call this configure method. The code is as follows:


    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IdentityDbContext dbContext)
    {
        app.UseDeveloperExceptionPage();           
        app.UseStaticFiles();          
        app.UseMvcWithDefaultRoute();
    }

The above code shows how to add MVC to the ASP. Net coreRequest processing pipelineNext, we are going to implement the custom middleware.

Create custom Middleware

Can useIApplicationBuilderInterface extension method to build your middleware. For code maintainability, it is recommended to put the customized middleware logic in a separate class or a separate project, so that you do not need to update the code of the business logic layer when updating these codes.

There are many ways to build custom middleware. I’m going to demonstrate the simplest one. First, create a middleware namedMyCustomMiddlewareThe skeleton code of the CS class is as follows:


    public class MyCustomMiddleware
    {
        //This is our custom middleware
    }

Next, add a requestdelegate parameter in the constructor of the class. The signature of the requestdelegate delegate is to receiveHttpContextParameter and return the task. The following is the modified mycustommiddleware.


    public class MyCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public MyCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    }

Execute custom Middleware

Now you need toMyCustomMiddlewareProvides an executable method forProcessing flowExecute this method when executing this class, which is the followingInvoke, some friends may want to ask, why must it beInvokeMethod, can it be other? No, this is the method name agreed in ASP. Net core middleware,InvokeMethod, you can implement monitoring or modificationRequestorResposne


    public class MyCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public MyCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            if (!httpContext.Request.Headers.Keys.Contains("Authentication-Key"))
            {
                httpContext.Response.StatusCode = 400;
                await httpContext.Response.WriteAsync("Authentication key is missing...");
                return;
            }
            else
            {
                //Write code here to validate the authentication key.
            }
            await _next.Invoke(httpContext);
        }
    }

Referring to the above code, the function of middleware is to judgerequest headerAre there any validauthentication key, if not, it will return specific error information to the client.

Create extension method

Next, for the just createdCustom MiddlewareCreate an extension method to make it easy tomiddleware Injected into pipeline, the official recommended practice is to IApplicationBuilder Interface. The following code shows how to implement it.


    public static class MyCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyCustomMiddleware>();
        }
    }

The last thing to do is toConfigureMethod, which is used under the app parameterUseMyCustomMiddleware()OK, as shown in the following code:


        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMyCustomMiddleware();
        }

Finally, run the program, as shown in the following figure:

How to customize Middleware in asp.net core

From the above output, we can see that my custom middleware works, and we can see that the practice of middleware makesWeb programThe scalability is greatly improved. If you want to know more about middleware, please refer to: https://docs.microsoft.com/en…

Translation link: https://www.infoworld.com/art…

Recommended Today

A brief introduction to CGI programming in Ruby

Ruby is a general language, not just a language used for web development, but ruby is the most common in web applications and web tools. With ruby, you can not only write your own SMTP server, FTP program, or Ruby web server, but also use ruby for CGI programming. Next, let’s take a moment to […]