当前位置:网站首页>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 .

边栏推荐
- The principle of fluent 2 rendering and how to realize video rendering
- Pointer understanding
- Tetris source code (color version)
- Don't fight for big companies
- H - Arctic network (minimum spanning tree)
- 001 data type [basic]
- The short video and live broadcast incubation training camp with goods opens nationwide enrollment!
- 终于看懂科学了!200张图领略人类智慧的巅峰
- Scattered knowledge of C language (unfinished)
- Openresty built in variable
猜你喜欢

About pickle module - 6 points that beginners must know

4.12 input() input function and comments

【算法篇】四种链表总结完毕,顺手刷了两道面试题

Web technology sharing | whiteboard toolbar encapsulation of Web

各省GDP可视化案列,附带csv Metabase处理

Oculus quest2 | unity configures the oculus quest2 development environment and packages an application for real machine testing

4.4 string

Policy Center > Misrepresentation

(Niuke) BFS

Summary of system stability construction practice
随机推荐
Policy Center > Google Play‘s Target API Level Policy
1151 LCA in a binary tree (30 points)
It's so brain - burning that no wonder programmers lose their hair
String connector
Joint examination for management -- sample composition
Tetris source code (color version)
The principle of fluent 2 rendering and how to realize video rendering
Openresty built in variable
A. Theatre Square(codefore)
Kindle down, ireader relay
Review 2021, embrace change and live up to Shaohua
Noj1042 - electronic mouse running through maze
Oracle中的With As 子查询
iMeta | 叶茂/时玉等综述环境微生物组中胞内与胞外基因的动态穿梭与生态功能...
4.12 input() input function and comments
Abstract meaning
Npumcm selection question 3 and acmc2020a
容器常用命令
Management joint examination - mathematical formula
from Crypto. Cipher import AES could not find the solution record with module error