官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1app
中间件的定义:中间件是组装到应用程序管道中以处理请求和响应的软件ui
ASP.NET Core请求流程由一系列请求委托组成,以下图:this
编写中间件:中间件编写在一个类里,并经过扩展方法暴露spa
一、将中间件委托移动到一个类:code
public class RequestCustomeMiddleware { private readonly RequestDelegate _next; public RequestCultureMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { //...... // do something // Call the next delegate/middleware in the pipeline return this._next(context); } }
二、经过扩展方法暴露中间件:中间件
public static class RequestCustomMiddlewareExtensions { public static IApplicationBuilder UseRequestCustomCulture( this IApplicationBuilder builder) { return builder.UseMiddleware<RequestCustomMiddleware>(); } }
三、在Startup类的Configure方法里调用中间件:blog
public void Configure(IApplicationBuilder app) { app.UseRequestCulture(); }