ASP.NET CORE Middleware Realization Principles and Use French

Briefly describe the realization ideas of asp.net core middleware

Original address: https://www.cnblogs.com/shengyu-kmust/p/ 11583974.html

The process of an http request is the process of performing logical processing on a Request request several times, and finally setting the Response. From the perspective of code implementation, since both Request and Response are in HttpContext, this process can be expressed as a “delegate function with an httpContext as input”, that is, delegate Task RequestDelegate (HttpContext context). To facilitate the description of this article, we Temporarily call this delegate function “request processing logic”

share picture

p>

The role of middleware is to add a processing logic after the request. This processing logic takes the “previous request processing logic” as input and is processed by the middleware itself After that, a “new request processing logic” is returned. So from the code, the “middleware” can be expressed as a delegate that takes a “request processing logic” as input and returns another “request processing logic”, that is, Func. And multiple middleware is represented as List>.

Share a picture

The core function of Asp.net core middleware is how to merge a series of middleware into a “request processing logic” process, that is, how to merge List> to generate a RequestDelegate. The merge logic is as follows

Share pictures

Share pictures

There are two places to pay attention to the above code

1 Asp.net core will add a “404” processing middleware at the end of the request by default.

2. When merging, the components are reversed and then recycled

Because the first added middleware must be executed first, when merging, the first middleware must be the last Merging, that is, recycle and merge middleware after reverse order

How to use middleware

There are four ways to use middleware : Use, Run, Map and Middleware class, but the first three methods ultimately call the Use method. Let’s take a look at the implementation logic of the Use method, as follows

share picture

The use method is only added at the end of the middleware list (_components) A middleware

The following describes the usage of the four methods in detail

Use of Use< /h3>

There are two usages of Ues

Usage one

Call IApplicationBuilder Use(Func middleware), this usage needs to be controlled in the middleware delegate Whether you want to enter the next middleware, and create a RequestDelegate yourself and return, the writing will be more complicated.

The example is as follows

share picture

< p>Usage two

Call IApplicationBuilder Use(this IApplicationBuilder app, Func, Task> middleware), this is an extension method, this method does not need to create RequestDelegate yourself And return, the writing is relatively concise. The method it finally calls is still the implementation in Usage 1. The implementation code of this method is as follows.

Share pictures

The example is as follows

share picture

Note: The above two Use usages do not call the next middleware in the second middleware. This is to ensure that the http request does not enter the default last 404 middleware of asp.net core, because the last 404 middleware sets the status code, and once the response body has been written before, the status cannot be changed. code or request header, otherwise an error will be reported. Microsoft’s official documents require the use of middleware to follow the following rules: if the response body changes, do not call the next middleware to avoid the pollution of the httpcontext content of the previous middleware by the next middleware. (The examples in this article are for demonstration purposes, and this convention is not followed)

Share pictures

Usage of run

h3>

The implementation code of the run method is as follows

Share a picture

share picture

Note: As can be seen from the implementation code of the run method, run will not execute the next middleware, so the middleware after the first middle run method will not work. Therefore, it is usually placed at the end of the middleware when running

Map usage

Map is actually not the usage of middleware, but a new “middleware request route branch”. In this “branch”, you can use use again And run method to component a new middleware logic.

The example is as follows

share picture

As ​​in the above example, the middleware in the map will only be enabled when the request address matches the /test.

< h3>Usage of Middleware class

Middleware class does not need to inherit any class or interface, but it must have the name Invoke, the return type is Task, and the first parameter is the HttpContext type Methods.

The example is as follows

share picture

< p>Share a picture

< p>

Introduction of Asp.net core built-in middleware

< tbody>

Middleware name

How to use And description

Authentication

App.UseAuthentication, verify the current requesting user, and set HttpContext.User, when OAuth callbacks, it will stop the execution of the next middleware. Put it in front of the middleware to be used for user authentication

Static File

app.UseStaticFiles(), to determine whether the current request is a static file, if it is, the execution of the next middleware is aborted, otherwise the next middleware is continued. Put it at the top of the pipeline

Response Caching

app.UseResponseCaching(), caching middleware

< p>MVC

app.UseMvc(), introduce MVC into the middleware pipeline, if the requested address can find the corresponding MVC Routing, the execution of the next middleware is aborted. Put it at the end of the pipeline.

Exception

app.UseDeveloperExceptionPage(); or app.UseExceptionHandler(); is used to handle the exception information of the program. Put it at the top of the pipeline

Authorization

Authorize middleware. No direct reference is required, App.UseMvc() will be called internally and used in conjunction with app.UseAuthentication().

Summary of middleware

1. Use four methods: use, run, map and middleware class

2. When using multiple middleware, pay attention to the order of middleware

3 When designing middleware, please follow the principle of “separation of responsibilities”, that is, a middleware only deals with “single responsibility”, such as verifying users and authorization.

4. If you modify the response body, please do not execute the next middleware

Leave a Comment

Your email address will not be published.