《ASP.NET Core 6 框架解密》 总结,笔记:
如下图,主要是几种委托的写法。
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接口,如何注册成单利,实现类中可以注入相关服务。
第一次知道中间件还可以按约定实现。
例子比较简单,看一遍就明白了: