.Net Core middleware

Table of contents

1. What is middleware

Second, the use of middleware

3. Three concepts of middleware

4. Custom middleware

5. ASP.NET Core comes with middleware components

6. The difference between middleware and filter


1. What is middleware

         When browsing a website or using a mobile app to load content, the browser or mobile app is actually sending an HTTP request to the web server. After receiving the HTTP request, the server will perform a series of processing on the user's request, such as checking the authentication information of the request, processing the request header, checking whether there is a corresponding server-side response cache, and finding the controller class corresponding to the request After the operation method in the controller class is executed, the server will also perform a series of processing, such as saving the response cache, setting the cache header, setting the CORS header, and compressing the response content. If this series of operations are all hard-coded in ASP.NET Core, the code coupling will be too high, and processing logic cannot be assembled on demand. Therefore, the basic framework only completes necessary tasks such as scheduling of HTTP requests and parsing of messages, and other optional tasks are provided by different middleware. 

 Middleware refers to the software connected between system software and application software to facilitate communication between software. These middleware form a pipeline. The execution process of the entire ASP.NET Core is that HTTP requests and responses are assembled in the order of middleware The process of transferring between middleware. Developers can freely combine the middleware that makes up the pipeline as needed, such as adjusting the order of middleware, adding or deleting middleware, defining middleware, and so on.

Summarize:

1. Middleware is software that is assembled into the application pipeline to process requests and responses.
2. Each component chooses whether to pass the request on to the next component in the pipeline.
3. Each component can perform work before and after calling the next component in the pipeline.
4. Request delegates are used to build request pipelines and process each HTTP request.

Second, the use of middleware

A common scenario for middleware is logging. Middleware makes it easy to log requests (including URLs and routes) to a logging system for later analysis.

Middleware is also a good place for authorization and authentication, diagnostics, exception logging and handling.

In short, middleware can be used for logic that is not specific to the business domain, and for actions that need to happen on every request or on most requests.

3. Three concepts of middleware

Map、Use、Run。

Map: Used to define which requests a pipeline can handle

Use and Run: used to define pipelines, a pipeline consists of several Uses and a Run, each Use introduces a middleware, and Run is used to execute the final core application logic 

1. There is only one parameter of the RequestDelegate delegate type in the Run() method, and there is no Next parameter, so the Run() method is also called terminal middleware, and will not pass the request to the next middleware, that is, a "short circuit" occurs.

// Run方法向应用程序的请求管道中添加一个RequestDelegate委托
// 放在管道最后面,终端中间件
app.Run(handler: async context =>
{
    await context.Response.WriteAsync(text: "Hello World1\r\n");
});
app.Run(handler: async context =>
{
    await context.Response.WriteAsync(text: "Hello World2\r\n");
});

2. The parameter of the Use() method is a Func delegate, the input parameter is a RequestDelegate type delegate, and the return parameter is also a RequestDelegate type delegate, which means calling the next middleware

// 向应用程序的请求管道中添加一个Func委托,这个委托其实就是所谓的中间件。
// context参数是HttpContext,表示HTTP请求的上下文对象
// next参数表示管道中的下一个中间件委托,如果不调用next,则会使管道短路
// 用Use可以将多个中间件链接在一起
app.Use(async (context, next) =>
{
    await context.Response.WriteAsync(text: "hello Use1\r\n");
    // 调用下一个委托
    await next();
});
app.Use(async (context, next) =>
{
    await context.Response.WriteAsync(text: "hello Use2\r\n");
    // 调用下一个委托
    await next();
});

4. Custom middleware

      Middleware follows the explicit dependencies principle and exposes all dependencies in its constructor. Middleware can take advantage of the UseMiddleware extension method to inject services directly through their constructors. Dependency injected services are populated automatically.

ASP.NET Core agrees that middleware classes must include the following:

1. A public constructor with a parameter of type RequestDelegate.

2. There must be a public method named Invoke or InvokeAsync. This method must meet two conditions: the return type of the method is Task, and the first parameter of the method must be of type HttpContext.

Customize a middleware that records IP, and create a new class RequestIPMiddleware

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace MiddlewareDemo.Middleware
{
    /// <summary>
    /// 记录IP地址的中间件
    /// </summary>
    public class RequestIPMiddleware
    {
        // 私有字段
        private readonly RequestDelegate _next;
        /// <summary>
        /// 公共构造函数,参数是RequestDelegate类型
        /// 通过构造函数进行注入,依赖注入服务会自动完成注入
        /// </summary>
        /// <param name="next"></param>
        public RequestIPMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        /// <summary>
        /// Invoke方法
        /// 返回值是Task,参数类型是HttpContext
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            await context.Response.WriteAsync($"User IP:{context.Connection.RemoteIpAddress.ToString()}\r\n");
            // 调用管道中的下一个委托
            await _next.Invoke(context);
        }
    }
}

Create an extension method to extend IApplicationBuilder

using Microsoft.AspNetCore.Builder;
namespace MiddlewareDemo.Middleware
{
    public static class RequestIPExtensions
    {
        /// <summary>
        /// 扩展方法,对IApplicationBuilder进行扩展
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseRequestIP(this IApplicationBuilder builder)
        {
            // UseMiddleware<T>
            return builder.UseMiddleware<RequestIPMiddleware>();
        }
    }
}

Finally use the custom middleware in the Configure method of the Startup class

// 使用自定义中间件
app.UseRequestIP();

5. ASP.NET Core comes with middleware components

6. The difference between middleware and filter

       Both middleware and filters are a kind of AOP thinking. The filter is more suitable for the business. It focuses on the application itself and how to realize the business, such as formatting the output result and performing data verification on the requested ViewModel. At this time, the filter must be used. Filter is a part of MVC, it can intercept some information of your Action context, but middleware does not have this ability. Filters can be thought of as a function of add-on, which is simply a feature that middleware exhibits incidentally. Middleware is an important part of the pipeline model and is indispensable, but filters can be absent.

Guess you like

Origin blog.csdn.net/xxxcAxx/article/details/128356885