当前位置:首页 > Web开发 > 正文

dotnet core 中间件

2024-03-31 Web开发

标签:

## 官方说明

中间件是一种装配到应用管道以措置惩罚惩罚请求和响应的软件。 每个组件:

选择是否将请求通报到管道中的下一个组件。

可在管道中的下一个组件前后执行事情。

请求委托用于生成请求管道。 请求委托措置惩罚惩罚每个 HTTP 请求。

使用 RunMap 和 Use 扩展要领来配置请求委托。 可将一个单独的请求委托并行指定为匿名要领(称为并行中间件),或在可重用的类中对其进行界说。 这些可重用的类和并行匿名要领即为中间件 ,也叫中间件组件 。 请求管道中的每其中间件组件卖力挪用管道中的下一个组件,,或使管道短路。 傍边间件短路时,它被称为“终端中间件” ,因为它阻止中间件进一步措置惩罚惩罚请求。

## 执行挨次示例图

技术图片

## 实测一下

++新建dotnet core 3.1 web 项目++
在 ==Startup== 的 ==Configure== 中

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(async (context, next) => { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); await context.Response.WriteAsync("Middleware 1 Start \n"); await next.Invoke(); await context.Response.WriteAsync("Middleware 1 End \n"); stopWatch.Stop(); Console.WriteLine($"响应:{stopWatch.ElapsedMilliseconds}"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Middleware 2 Start \n"); await next.Invoke(); await context.Response.WriteAsync("Middleware 2 End \n"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Middleware 2 Start \n"); await next.Invoke(); await context.Response.WriteAsync("Middleware 2 End \n"); }); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World! \n"); }); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Middleware Use Last Start"); await next.Invoke(); await context.Response.WriteAsync("Middleware Use Last End"); }); } } 运行功效

技术图片

可以看到凭据挨次执行了 Middleware 1 Middleware 2 ,最后一个注册的中间件没有被执行,因为mvc中,如果请求与路由匹配,则为终端,短路了最后一其中间件的措置惩罚惩罚。

使用Run可以注册终端中间件,插手到 Middleware 2 下面

app.Run(async (context) => { await context.Response.WriteAsync("Middleware 3 \n"); }); 运行功效

技术图片

自界说

自界说类

public class MyMiddleware1 { private readonly RequestDelegate _next; public MyMiddleware1(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { await context.Response.WriteAsync("MyMiddleware1 Start \n"); await _next.Invoke(context); await context.Response.WriteAsync("MyMiddleware1 End \n"); } }

Startup中 app.UseMiddleware<MyMiddleware1>(); 注册中间件

运行功效

技术图片

实现IMiddleware

public class MyMiddleware2 : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { await context.Response.WriteAsync("MyMiddleware2 Start \n"); await next.Invoke(context); await context.Response.WriteAsync("MyMiddleware2 End \n"); } }

Startup中 app.UseMiddleware<MyMiddleware2>(); 注册中间件

ConfigureServices中向IOC容器注册services.AddSingleton<MyMiddleware2>();

运行功效

技术图片

检察源码看看这俩种方法的区别
class UseMiddlewareExtensions

关键代码

internal const string InvokeMethodName = "Invoke"; internal const string InvokeAsyncMethodName = "InvokeAsync"; public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args);

如果实现IMiddleware

if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo())) { // IMiddleware doesn't support passing args directly since it's // activated from the container if (args.Length > 0) { throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware))); } return UseMiddlewareInterface(app, middleware); }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/31981.html