asp.net core 自定義中間件

官方文檔: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(); }
相關文章
相關標籤/搜索