当前位置:网站首页>ASP. Net core Middleware
ASP. Net core Middleware
2022-06-30 15:41:00 【zhoubangbang1】
Middleware is a kind of software assembled into the application pipeline to handle requests and responses . Each component :
1. Choose whether to pass the request to the next component in the pipeline .
2. Work can be performed before and after the next component in the pipeline .
The request delegate is used to generate the request pipeline . Request delegates to process each HTTP request .
Use Run 、Map and Use Extend the method to configure the request delegate . A separate request delegate can be specified as an anonymous method in parallel ( It's called middleware ), Or define it in a reusable class . These reusable classes and parallel anonymous methods are called middleware , Also called middleware component . Each middleware component in the request pipeline is responsible for calling the next component in the pipeline , Or short-circuit the pipe . When the middleware is short circuited , It is called “ Terminal Middleware ” , Because it prevents the middleware from further processing requests .
Using middleware #
ASP.NET Core Middleware model is that we can develop our own middleware quickly , Complete the extension of the application , Let's start with a simple example of middleware development .
Run:
effect : first Run Delegate terminated pipeline .
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
}
}Running results :

Such results do not seem to clearly show Run The role of , Next, let's introduce a simple example :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, .Net");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, Python!");
});
}Running results :

From these two simple pieces of code, we can see , Use Run Method to run a delegate , It is a simple middleware , It intercepts all requests , Return a piece of text in response . also Run The Commission terminated the operation of the pipeline , It is also called terminal middleware .
Use
Use Links multiple request delegates together .next Parameter represents the next delegate in the pipeline . Can be called by not calling next The parameter short-circuited the pipe . Operations can usually be performed before or after the next delegate , This is shown in the following example :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
//await next.Invoke();
await context.Response.WriteAsync("After Use1 \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}Code execution result :

Did you think the result would be like this ? Would you say Run Is the termination Middleware , Why is the corresponding content not displayed ? Let's think about it ....
I believe everyone should have guessed , We were introducing it before Use When I said
Use Links multiple request delegates together .next Parameter represents the next delegate in the pipeline . Can be called by not calling next The parameter short-circuited the pipe .
Let's look at the next example :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
await next.Invoke();
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}Let's guess what it will be ? I believe everyone can get , You won't paste the results , You can experiment it yourself
Middleware sequence
ASP.NET Core The request pipeline contains a series of request delegates , In turn, calls . The following diagram illustrates this concept . Execute along the black arrow .

towards Startup.Configure Method the order in which middleware components are added defines the order in which these components are called for requests , And the reverse order of responses . This sequence is important for security 、 Performance and functionality are critical .
Next let's look at the example :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use1 \r\n");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}Running results :

The execution sequence of middleware may not be well understood through the above experiments , Let's take another example :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use1 \r\n");
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}Running results :

Through the experimental comparison of the two , We can find out , The running sequence of middleware is clockwise , Middleware ,next The previous one is executed from top to bottom according to the sorting order of middleware , stay next The subsequent code is executed in the reverse order of the middleware .
Customize ASP.NET Core middleware
Middleware is usually encapsulated in a class , And use extended methods to expose .

Middleware delegates are moved to classes :
stay Middlewares Created in RequestMiddlewareExtensions class :
public class RequestTestMiddleware
{
private readonly RequestDelegate _next;
public RequestTestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("start RequestTestMiddleware \r\n");
await _next(context);
await context.Response.WriteAsync("end RequestTestMiddleware \r\n");
}
}
Insert the middleware as follows :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// app.UseRequestCulture();
app.UseMiddleware<RequestTestMiddleware>();
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use1 \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}
Execution results :

Expose middleware through extension methods :
Write extension methods RequestMiddlewareExtensions
public static class RequestMiddlewareExtensions
{
public static IApplicationBuilder UseRequestCulture(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestTestMiddleware>();
}
}
stay Startup Class to create a request processing pipeline for the application :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRequestCulture();
//app.UseMiddleware<RequestTestMiddleware>();
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await context.Response.WriteAsync("before Use1 \r\n");
await next.Invoke();
await context.Response.WriteAsync("After Use1 \r\n");
// Do logging or other work that doesn't write to the Response.
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.\r\n");
});
}
The implementation result is the same as above .
This is my wechat public number , I hope to grow up with you , I will keep it updated once a day or so .

边栏推荐
- 《你的灯亮着吗》开始解决问题前,得先知道“真问题”是什么
- Mysql database - create user name & modify permission
- Kindle倒下,iReader接力
- Four solutions to cross domain problems
- Model system: Sword (1)
- A little idea about big experiment data
- 4.4 string
- 4.8 data type conversion
- Joint examination for management -- sample composition
- [matlab] 3D drawing summary
猜你喜欢

Pycharm----xx. So cannot open shared object file problem solving

Single cycle CPU of the design group of West University of Technology

4.12 input() input function and comments

What would you choose between architecture optimization and business iteration?
![[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics](/img/91/2a94749d64d153ef1caf81345594a4.png)
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics

Advanced functions of ES6 operation array map (), filter (), reduce()

Npumcm selection question 3 and acmc2020a

FoxPro and I

Technology sharing | anyrtc service single port design

Advanced C language - pointer 3 - knowledge points sorting
随机推荐
Industry analysis | the future of real-time audio and video
[leetcode] linked list sorting (gradually increasing the space-time complexity)
About pickle module - 6 points that beginners must know
O - ACM contest and blackout (minimum spanning tree, Kruskal)
波导的种类
openresty 内置变量
linux下新建Mysql数据库并导入sql文件
4.8 data type conversion
iMeta | 叶茂/时玉等综述环境微生物组中胞内与胞外基因的动态穿梭与生态功能...
How to browse mobile web pages on your computer
Expressions in if statements
比亚迪越来越像华为?
Preliminary study on AI noise reduction evaluation system of sound network
4.3 variables and assignments
Visualization of provincial GDP with CSV metabase processing
The principle of fluent 2 rendering and how to realize video rendering
Developer practice - the future of Agora home AI audio and video
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
Soap comparison result file description
[matlab] 2D drawing summary