.NetCore中的Middleware是装配到管道处理请求和响应的组件;每个组件都可以决定是否继续进入下一个管道、并且可以在进入下一个管道前后执行逻辑;
最后一个管道或者中断管道的中间件叫终端中间件;
1、创建中间件管道IApplicationBuilder
app.Run()拦截请求后中断请求,多个Run()只执行第一个;
app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("截获请求!并在此后中断管道"); }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("排序第二个的RUN"); });
2、连接下一个管道 Use()
使用next.invoke调用下一个管道,在向客户端发送响应后,不允许调用 next.Invoke,会引发异常
app.Use(async (context, next) => { // 执行逻辑,但不能写Response //调用管道中的下一个委托 await next.Invoke(); // 执行逻辑,如日志等,但不能写Response }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("截获请求!并在此后中断管道"); }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("排序第二个的RUN"); });
3、通过路径或条件处理管道 Map()
public class Startup { private static void HandleBranch(IApplicationBuilder app) { app.Run(async context => { var branchVer = context.Request.Query["branch"]; await context.Response.WriteAsync($"Branch used = {branchVer}"); }); } private static void HandleMapTest2(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Map Test 2"); }); } public void Configure(IApplicationBuilder app) { app.MapWhen(context => context.Request.Query.ContainsKey("branch"), HandleBranch);//localhost:1234/?branch=master app.Map("/map2", HandleMapTest2);//localhost:1234/map2 app.Run(async context => { await context.Response.WriteAsync("Hello from non-Map delegate. <p>"); }); } }
4、中间件的顺序很重要
异常/错误处理
HTTP 严格传输安全协议
HTTPS 重定向
静态文件服务器
Cookie 策略实施
身份验证
会话
MVC
app.UseExceptionHandler("/Home/Error"); // Call first to catch exceptions app.UseStaticFiles(); // Return static files and end pipeline. app.UseAuthentication(); // Authenticate before you access app.UseMvcWithDefaultRoute();
资源
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/index?view=aspnetcore-2.2