Core端點路由在ASP.NET中的作用有哪些?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
端點路由(Endpoint Routing)最早出現在ASP.NET Core2.2,在ASP.NET Core3.0提升為一等公民。
Endpoint Routing的動機
在端點路由出現之前,我們一般在請求處理管道的末尾,定義MVC中間件解析路由。這種方式意味著在處理管道中,MVC中間件之前的中間件將無法獲得路由信息。
路由信息對于某些中間件非常有用,比如CORS、認證中間件(認證過程可能會用到路由信息)。
同時端點路由提煉出端點
概念,解耦路由匹配邏輯、請求分發。
Endpoint Routing中間件
由一對中間件組成:
UseRouting 將路由匹配添加到中間件管道。該中間件查看應用程序中定義的端點集合,并根據請求選擇最佳匹配。UseEndpoints 將端點執行添加到中間件管道。
MapGet、MapPost等方法將 處理邏輯連接到路由系統;
其他方法將 ASP.NET Core框架特性連接到路由系統。
處于這對中間件上游的 中間件: 始終無法感知 Endpoint;
處于這對中間件之間的 中間件,將會感知到Endpoint,并有能力執行附加處理邏輯;
UseEndpoint是一個終點中間件;
沒有匹配,則進入UseEndpoint之后的中間件。
放置在UseRouting
、UseEndpoints
之間的認證授權中間件可以:
感知被匹配的端點信息;在調度到Endpoint之前,應用授權策略。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Matches request to an endpoint. app.UseRouting(); // Endpoint aware middleware. // Middleware can use metadata from the matched endpoint. app.UseAuthentication(); app.UseAuthorization(); // Execute the matched endpoint. app.UseEndpoints(endpoints => { // Configure the Health Check endpoint and require an authorized user. endpoints.MapHealthChecks("/healthz").RequireAuthorization(); // Configure another endpoint, no authorization requirements. endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); }
以上在/health
定義了健康檢查,該端點定義了IAuthorizeData
metadata,要求先認證再執行健康檢查。
我們在UseRouting、UseEndpoints之間添加一點口水代碼:感知端點:
app.Use(next => context => { var endpoint = context.GetEndpoint(); if (endpoint is null) { return Task.CompletedTask; } Console.WriteLine($"Endpoint: {endpoint.DisplayName}"); if (endpoint is RouteEndpoint routeEndpoint) { Console.WriteLine("Endpoint has route pattern: " + routeEndpoint.RoutePattern.RawText); } foreach (var metadata in endpoint.Metadata) { Console.WriteLine($"Endpoint has metadata: {metadata}"); } return next(context); });
當請求/healthz
時,感知到AuthorizeAttribute
metadata
故猜想認證授權中間件要對/healthz
起作用,必然會對這個 AuthorizeAttribute
metadata有所反應。
于是翻閱GithubAuthorizationMiddleware
3.0源碼:發現確實關注了Endpoint
// ---- 截取自https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authorization/Policy/src/AuthorizationMiddleware.cs----- if (endpoint != null) { context.Items[AuthorizationMiddlewareInvokedWithEndpointKey] = AuthorizationMiddlewareWithEndpointInvokedValue; } var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>(); var policy = await AuthorizationPolicy.CombineAsync(_policyProvider, authorizeData); if (policy == null) { await _next(context); return; } var policyEvaluator = context.RequestServices.GetRequiredService<IPolicyEvaluator>(); ......
而AuthorizeAttribute
確實是實現了IAuthorizeData
接口。
binggo, 猜想得到源碼驗證。
結論
端點路由:允許ASP.NET Core應用程序在中間件管道的早期確定要調度的端點,
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。