.NetCore中的Middleware是装配到管道处理请求和响应的组件;每一个组件均可以决定是否继续进入下一个管道、而且能够在进入下一个管道先后执行逻辑;安全
最后一个管道或者中断管道的中间件叫终端中间件;服务器
一、建立中间件管道IApplicationBuilderapp
app.Run()拦截请求后中断请求,多个Run()只执行第一个;async
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"); });
二、链接下一个管道 Use()ui
使用next.invoke调用下一个管道,在向客户端发送响应后,不容许调用 next.Invoke,会引起异常spa
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"); });
三、经过路径或条件处理管道 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>"); }); } }
四、中间件的顺序很重要code
异常/错误处理
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();
资源blog
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/index?view=aspnetcore-2.2