1.HTTP请求管线(Http Request Pipeline)
2.中间件(Middleware)
2.1概述
1.中间件是HTTP请求管线中使用的一段代码
2.Asp .Net Core应用程序可以有n个中间件
3.中间件的顺序在执行过程中非常重要。
中间件例如:
1.Routing
2.Authentication
3.Add excretion page …
2.2Run(),Use(),Next()和Map()在中间件中的使用
1.Run()方法用于完成中间件的执行
2.Use()方法用于在管线中插入新的中间件
3.Next()方法用于将执行传递给下一个中间件
4.Map()方法用于将中间件映射到特定的URL
2.2.1 Run()方法
添加一个终端中间件委托到应用到请求管线。
IApplicationBuilder.Run(RequestDelegate handler)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("hello Run");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("hello Run2");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endponits =>
{
endponits.MapControllers();
});
}
运行结果:
2.2.1 Use()&Next()
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("hello Run");
//});
app.Use(async (context,next) =>
{
await context.Response.WriteAsync("hello Use1 \n");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("hello Run2");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endponits =>
{
endponits.MapControllers();
});
}
运行结果:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//app.Run(async (context) =>
//{
// await context.Response.WriteAsync("hello Run");
//});
app.Use(async (co