探究ASP.NET Core Middleware實(shí)現(xiàn)方法
概念
ASP.NET Core Middleware是在應(yīng)用程序處理管道pipeline中用于處理請(qǐng)求和操作響應(yīng)的組件。
每個(gè)組件:
- 在pipeline中判斷是否將請(qǐng)求傳遞給下一個(gè)組件
- 在處理管道的下個(gè)組件執(zhí)行之前和之后執(zhí)行一些工作, HttpContxt對(duì)象能跨域請(qǐng)求、響應(yīng)的執(zhí)行周期
特性和行為
ASP.NET Core處理管道由一系列請(qǐng)求委托組成,一環(huán)接一環(huán)的被調(diào)用, 下面給出自己繪制的Middleware pipeline流程圖:
從上圖可以看出,請(qǐng)求自進(jìn)入處理管道,經(jīng)歷了四個(gè)中間件,每個(gè)中間件都包含后續(xù)緊鄰中間件 執(zhí)行委托(next)的引用,同時(shí)每個(gè)中間件在交棒之前和交棒之后可以自行決定參與一些Http請(qǐng)求和響應(yīng)的邏輯處理。
每個(gè)中間件還可以決定不將請(qǐng)求轉(zhuǎn)發(fā)給下一個(gè)委托,這稱(chēng)為請(qǐng)求管道的短路(短路是有必要的,某些專(zhuān)有中間件比如 StaticFileMiddleware 可以在完成功能之后,避免請(qǐng)求被轉(zhuǎn)發(fā)到其他動(dòng)態(tài)處理過(guò)程)。
源碼實(shí)現(xiàn)
觀察一個(gè)標(biāo)準(zhǔn)的中間件代碼的寫(xiě)法和用法:
using System.Threading.Tasks; using Alyio.AspNetCore.ApiMessages; using Gridsum.WebDissector.Common; using Microsoft.AspNetCore.Http; namespace Gridsum.WebDissector { sealed class AuthorizationMiddleware { private readonly RequestDelegate _next; // 下一個(gè)中間件執(zhí)行委托的引用 public AuthorizationMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) // 貫穿始終的HttpContext對(duì)象 { if (context.Request.Path.Value.StartsWith("/api/")) { return _next(context); } if (context.User.Identity.IsAuthenticated && context.User().DisallowBrowseWebsite) { throw new ForbiddenMessage("You are not allow to browse the website."); } return _next(context); } } } public static IApplicationBuilder UserAuthorization(this IApplicationBuilder app) { return app.UseMiddleware<AuthorizationMiddleware>(); } // 啟用該中間件,也就是注冊(cè)該中間件 app.UserAuthorization();
標(biāo)準(zhǔn)的中間件使用方式是如此簡(jiǎn)單明了,帶著幾個(gè)問(wèn)題探究一下源碼實(shí)現(xiàn)
(1).中間件傳參是怎樣完成的: app.UseMiddleware<Authorization>(AuthOption); 我們傳參的時(shí)候,為什么能自動(dòng)注入中間件構(gòu)造函數(shù)非第1個(gè)參數(shù)
(2).編寫(xiě)中間件的時(shí)候,為什么必須要定義特定的 Invoke/InvokeAsync 函數(shù)?
(3).設(shè)定中間件的順序很重要,中間件的嵌套順序是怎么確定的 ?
思考以上標(biāo)準(zhǔn)中間件的行為: 輸入下一個(gè)中間件的執(zhí)行委托Next, 定義當(dāng)前中間件的執(zhí)行委托Invoke/InvokeAsync;
每個(gè)中間件完成了 Func<RequestDelegate,RequestDelegate>這樣的行為;
通過(guò)參數(shù)next與下一個(gè)中間件的執(zhí)行委托Invoke/InvokeAsync 建立"鏈?zhǔn)?關(guān)系。
public delegate Task RequestDelegate(HttpContext context);
//-----------------節(jié)選自 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions------------------ /// <summary> /// Adds a middleware type to the application's request pipeline. /// </summary> /// <typeparam name="TMiddleware">The middleware type.</typeparam> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args) { return app.UseMiddleware(typeof(TMiddleware), args); } /// <summary> /// Adds a middleware type to the application's request pipeline. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="middleware">The middleware type.</param> /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args) { if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo())) { // IMiddleware doesn't support passing args directly since it's // activated from the container if (args.Length > 0) { throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware))); } return UseMiddlewareInterface(app, middleware); } var applicationServices = app.ApplicationServices; return app.Use(next => { var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public); // 執(zhí)行委托名稱(chēng)被限制為Invoke/InvokeAsync var invokeMethods = methods.Where(m => string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal) || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal) ).ToArray(); if (invokeMethods.Length > 1) { throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName)); } if (invokeMethods.Length == 0) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware)); } var methodInfo = invokeMethods[0]; if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType)) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task))); } var parameters = methodInfo.GetParameters(); if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext)) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext))); } var ctorArgs = new object[args.Length + 1]; ctorArgs[0] = next; Array.Copy(args, 0, ctorArgs, 1, args.Length); // 通過(guò)反射形成中間件實(shí)例的時(shí)候,構(gòu)造函數(shù)第一個(gè)參數(shù)被指定為 下一個(gè)中間件的執(zhí)行委托 var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs); if (parameters.Length == 1) { return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance); } // 當(dāng)前執(zhí)行委托除了可指定HttpContext參數(shù)以外, 還可以注入更多的依賴(lài)參數(shù) var factory = Compile<object>(methodInfo, parameters); return context => { var serviceProvider = context.RequestServices ?? applicationServices; if (serviceProvider == null) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider))); } return factory(instance, context, serviceProvider); }; }); } //-------------------節(jié)選自 Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder------------------- private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>(); publicIApplicationBuilder Use(Func<RequestDelegate,RequestDelegate> middleware) { this._components.Add(middleware); return this; } public RequestDelegate Build() { RequestDelegate app = context => { context.Response.StatusCode = 404; return Task.CompletedTask; }; foreach (var component in _components.Reverse()) { app = component(app); } return app; }
通過(guò)以上代碼我們可以看出:
- 注冊(cè)中間件的過(guò)程實(shí)際上,是給一個(gè) Type= List<Func<RequestDelegate, RequestDelegate>> 的容器依次添加元素的過(guò)程;
- 容器中每個(gè)元素對(duì)應(yīng)每個(gè)中間件的行為委托Func<RequestDelegate, RequestDelegate>, 這個(gè)行為委托包含2個(gè)關(guān)鍵行為:輸入下一個(gè)中間件的執(zhí)行委托next:RequestDelegate, 完成當(dāng)前中間件的Invoke函數(shù): RequestDelegate;
- 通過(guò)build方法完成前后中間件的鏈?zhǔn)絺髦店P(guān)系
分析源碼:回答上面的問(wèn)題:
- 使用反射構(gòu)造中間件的時(shí)候,第一個(gè)參數(shù)Array[0] 是下一個(gè)中間件的執(zhí)行委托
- 當(dāng)前中間件執(zhí)行委托 函數(shù)名稱(chēng)被限制為: Invoke/InvokeAsync, 函數(shù)支持傳入除HttpContext之外的參數(shù)
- 按照代碼順序添加進(jìn)入 _components容器, 通過(guò)后一個(gè)中間件的執(zhí)行委托 -----(指向)----> 前一個(gè)中間件的輸入執(zhí)行委托建立鏈?zhǔn)疥P(guān)系。
附:非標(biāo)準(zhǔn)中間件的用法
短路中間件、 分叉中間件、條件中間件
整個(gè)處理管道的形成,存在一些管道分叉或者臨時(shí)插入中間件的行為,一些重要方法可供使用
- Use方法是一個(gè)注冊(cè)中間件的簡(jiǎn)便寫(xiě)法
- Run方法是一個(gè)約定,一些中間件使用Run方法來(lái)完成管道的結(jié)尾
- Map擴(kuò)展方法:請(qǐng)求滿(mǎn)足指定路徑,將會(huì)執(zhí)行分叉管道,強(qiáng)調(diào)滿(mǎn)足 path
- MapWhen方法:HttpContext滿(mǎn)足條件,將會(huì)執(zhí)行分叉管道:
- UseWhen方法:HttpContext滿(mǎn)足條件 則插入中間件
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解ASP.NET Core中間件Middleware
- 理解ASP.NET Core 中間件(Middleware)
- ASP.NET Core Middleware的實(shí)現(xiàn)方法詳解
- ASP.NET Core應(yīng)用錯(cuò)誤處理之StatusCodePagesMiddleware中間件針對(duì)響應(yīng)碼呈現(xiàn)錯(cuò)誤頁(yè)面
- ASP.NET Core應(yīng)用錯(cuò)誤處理之ExceptionHandlerMiddleware中間件呈現(xiàn)“定制化錯(cuò)誤頁(yè)面”
- ASP.NET Core應(yīng)用錯(cuò)誤處理之DeveloperExceptionPageMiddleware中間件呈現(xiàn)“開(kāi)發(fā)者異常頁(yè)面”
- 利用Asp.Net Core的MiddleWare思想如何處理復(fù)雜業(yè)務(wù)流程詳解
- ASP.NET?Core使用Middleware設(shè)置有條件允許訪問(wèn)路由
相關(guān)文章
The remote procedure call failed and did not execute的解決辦法
打開(kāi)IIS隨便訪問(wèn)一個(gè).asp文件,提示The remote procedure call failed and did not execute2009-11-11.Net Core項(xiàng)目中NLog整合Exceptionless實(shí)例
這篇文章主要介紹了.Net Core項(xiàng)目中NLog整合Exceptionless實(shí)例,NLog主要是收集程序中的日志,Exceptionless可以統(tǒng)一收集管理并展示出來(lái)程序的日志,兩者結(jié)合使用,相得益彰。感興趣的小伙伴可以參考這篇文章2021-09-09asp.net網(wǎng)頁(yè)里面為什么找不到CS文件
這篇文章主要介紹了asp.net為什么網(wǎng)頁(yè)里面找不到CS文件,如何才能夠cs文件顯示出來(lái)2014-05-05在?Net7.0?環(huán)境下如何使用?RestSharp?發(fā)送?Http(FromBody和FromForm)請(qǐng)求
這篇文章主要介紹了在?Net7.0?環(huán)境下使用?RestSharp?發(fā)送?Http(FromBody和FromForm)請(qǐng)求,今天,我就兩個(gè)小的知識(shí)點(diǎn),就是通過(guò)使用?RestSharp?訪問(wèn)?WebAPI,提交?FromBody?和?FromForm?兩種方式的數(shù)據(jù),還是有些區(qū)別的,本文結(jié)合實(shí)例代碼介紹的非常詳細(xì),需要的朋友參考下吧2023-09-09asp.net UpdatePanel的簡(jiǎn)單用法
局部更新是ajax技術(shù)的最基本,也是最重要的用法,今天大概把a(bǔ)sp.net ajax中的局部更新控件 updatepanel的用法記錄下,大家可以共同探討2008-11-11asp.net 頁(yè)面編碼常見(jiàn)問(wèn)題小結(jié)
2010-06-06利用Service Fabric承載eShop On Containers的實(shí)現(xiàn)方法
下面小編就為大家分享一篇利用Service Fabric承載eShop On Containers的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01asp.net 頁(yè)面版文本框智能提示JSCode (升級(jí)版)
模擬百度,Google智能提示,非與服務(wù)器端交互的,數(shù)據(jù)源來(lái)自已經(jīng)綁定好的下拉列表。純客戶(hù)端腳本 升級(jí)版2009-12-12