Asp.net Core 中间件几种注册方式
《ASP.NET Core 6 框架解密》 总结,笔记:
1.RequestDelegate
- RequestDelegate委托对象作为参数调用了WebApplication对象的Run扩展方法。
- 该扩展方法只是注册了一个中间件,具体点,就是说这个扩展方法用于注册处于管道末端的中间件
如下图,主要是几种委托的写法。
RequestDelegate handler = context => context.Response.WriteAsync("Hello,World!"); WebApplicationBuilder builder = WebApplication.CreateBuilder(args); WebApplication app = builder.Build(); app.Run(handler); app.Run();
var app = WebApplication.Create(args); IApplicationBuilder builder = app; builder.Use(HelloMiddleware) .Use(WorldMiddleware); app.Run(); static RequestDelegate HelloMiddleware(RequestDelegate next) => async httpcontext => { await httpcontext.Response.WriteAsync("Hello,"); await next(httpcontext); }; static RequestDelegate WorldMiddleware(RequestDelegate next) => httpcontext => httpcontext.Response.WriteAsync("World!");
var app = WebApplication.Create(args); IApplicationBuilder builder = app; builder.Use(HelloMiddleware) .Use(WorldMiddleware); app.Run(); //Func<HttpContext,RequestDelegate,Task> //Func<HttpContext,Func<Task>,Task> static async Task HelloMiddleware(HttpContext context, RequestDelegate next) { await context.Response.WriteAsync("Hello,"); await next(context); } static Task WorldMiddleware(HttpContext context, RequestDelegate next) => context.Response.WriteAsync("World!");
- 其实很少会将中间件定义为上面的这三种形式,其中一种最直接的实现就是实现“ IMiddleware ”接口,它可以将依赖注入功能结合在一起,实现“ IMiddleware ”的类中可以注入服务。
2.实现IMiddleware接口实现
这个比较简单,实现IMiddleware接口,如何注册成单利,实现类中可以注入相关服务。
3.按照约定实现中间件
第一次知道中间件还可以按约定实现。
例子比较简单,看一遍就明白了:
本文作者:youliCC