官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1
中间件的定义:中间件是组装到应用程序管道中以处理请求和响应的软件
ASP.NET Core请求流程由一系列请求委托组成,如下图:
编写中间件:中间件编写在一个类里,并通过扩展方法暴露
1、将中间件委托移动到一个类:
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);
}
}
2、通过扩展方法暴露中间件:
public static class RequestCustomMiddlewareExtensions
{
public static IApplicationBuilder UseRequestCustomCulture(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestCustomMiddleware>();
}
}
3、在Startup类的Configure方法里调用中间件:
public void Configure(IApplicationBuilder app)
{
app.UseRequestCulture();
}