在本打算写一篇关于Identityserver4
的文章时候,确发现本身对EndPoint
-终结点路由还不是很了解,故暂时先放弃了IdentityServer4
的研究和编写;因此才产生了今天这篇关于EndPoint
(终结点路由) 的文章。web
仍是跟往常同样,打开电脑使用强大的Google 和百度搜索引擎查阅相关资料,以及打开Asp.net core 3.1 的源代码进行拜读,同时终于在个人实践及测试中对EndPoint
有了不同的认识,说到这里更加敬佩微软对Asp.net core 3.x 的框架中管道模型的设计。微信
我先来提出如下几个问题:app
Controller
的Action
的呢?EndPoint
跟普通路由又存在着什么样的关系?UseRouing()
、UseAuthorization()
、UserEndpoints()
这三个中间件的关系是什么呢?EndPoint
终结者路由来拦截Action 的执行而且记录相关操做日志?(时间有限,下一篇文章再来分享整理)Startup
代码咱们先来看一下Startup
中简化版的代码,代码以下:框架
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
程序启动阶段:asp.net
Controller
的核心服务注册到容器中去EndpointRoutingMiddleware
中间件注册到http管道中AuthorizationMiddleware
中间件注册到http管道中endpoints.MapControllers()
将本程序集定义的全部Controller
和Action
转换为一个个的EndPoint
放到路由中间件的配置对象RouteOptions
中EndpointMiddleware
中间件注册到http管道中app.UseRouting()
源代码以下:public static IApplicationBuilder UseRouting(this IApplicationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } VerifyRoutingServicesAreRegistered(builder); var endpointRouteBuilder = new DefaultEndpointRouteBuilder(builder); builder.Properties[EndpointRouteBuilder] = endpointRouteBuilder; return builder.UseMiddleware<EndpointRoutingMiddleware>(endpointRouteBuilder); }
EndpointRoutingMiddleware
中间件代码以下:async
internal sealed class EndpointRoutingMiddleware { private const string DiagnosticsEndpointMatchedKey = "Microsoft.AspNetCore.Routing.EndpointMatched"; private readonly MatcherFactory _matcherFactory; private readonly ILogger _logger; private readonly EndpointDataSource _endpointDataSource; private readonly DiagnosticListener _diagnosticListener; private readonly RequestDelegate _next; private Task<Matcher> _initializationTask; public EndpointRoutingMiddleware( MatcherFactory matcherFactory, ILogger<EndpointRoutingMiddleware> logger, IEndpointRouteBuilder endpointRouteBuilder, DiagnosticListener diagnosticListener, RequestDelegate next) { if (endpointRouteBuilder == null) { throw new ArgumentNullException(nameof(endpointRouteBuilder)); } _matcherFactory = matcherFactory ?? throw new ArgumentNullException(nameof(matcherFactory)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _diagnosticListener = diagnosticListener ?? throw new ArgumentNullException(nameof(diagnosticListener)); _next = next ?? throw new ArgumentNullException(nameof(next)); _endpointDataSource = new CompositeEndpointDataSource(endpointRouteBuilder.DataSources); } public Task Invoke(HttpContext httpContext) { // There's already an endpoint, skip maching completely var endpoint = httpContext.GetEndpoint(); if (endpoint != null) { Log.MatchSkipped(_logger, endpoint); return _next(httpContext); } // There's an inherent race condition between waiting for init and accessing the matcher // this is OK because once `_matcher` is initialized, it will not be set to null again. var matcherTask = InitializeAsync(); if (!matcherTask.IsCompletedSuccessfully) { return AwaitMatcher(this, httpContext, matcherTask); } var matchTask = matcherTask.Result.MatchAsync(httpContext); if (!matchTask.IsCompletedSuccessfully) { return AwaitMatch(this, httpContext, matchTask); } return SetRoutingAndContinue(httpContext); // Awaited fallbacks for when the Tasks do not synchronously complete static async Task AwaitMatcher(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task<Matcher> matcherTask) { var matcher = await matcherTask; await matcher.MatchAsync(httpContext); await middleware.SetRoutingAndContinue(httpContext); } static async Task AwaitMatch(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matchTask) { await matchTask; await middleware.SetRoutingAndContinue(httpContext); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private Task SetRoutingAndContinue(HttpContext httpContext) { // If there was no mutation of the endpoint then log failure var endpoint = httpContext.GetEndpoint(); if (endpoint == null) { Log.MatchFailure(_logger); } else { // Raise an event if the route matched if (_diagnosticListener.IsEnabled() && _diagnosticListener.IsEnabled(DiagnosticsEndpointMatchedKey)) { // We're just going to send the HttpContext since it has all of the relevant information _diagnosticListener.Write(DiagnosticsEndpointMatchedKey, httpContext); } Log.MatchSuccess(_logger, endpoint); } return _next(httpContext); } // Initialization is async to avoid blocking threads while reflection and things // of that nature take place. // // We've seen cases where startup is very slow if we allow multiple threads to race // while initializing the set of endpoints/routes. Doing CPU intensive work is a // blocking operation if you have a low core count and enough work to do. private Task<Matcher> InitializeAsync() { var initializationTask = _initializationTask; if (initializationTask != null) { return initializationTask; } return InitializeCoreAsync(); } private Task<Matcher> InitializeCoreAsync() { var initialization = new TaskCompletionSource<Matcher>(TaskCreationOptions.RunContinuationsAsynchronously); var initializationTask = Interlocked.CompareExchange(ref _initializationTask, initialization.Task, null); if (initializationTask != null) { // This thread lost the race, join the existing task. return initializationTask; } // This thread won the race, do the initialization. try { var matcher = _matcherFactory.CreateMatcher(_endpointDataSource); // Now replace the initialization task with one created with the default execution context. // This is important because capturing the execution context will leak memory in ASP.NET Core. using (ExecutionContext.SuppressFlow()) { _initializationTask = Task.FromResult(matcher); } // Complete the task, this will unblock any requests that came in while initializing. initialization.SetResult(matcher); return initialization.Task; } catch (Exception ex) { // Allow initialization to occur again. Since DataSources can change, it's possible // for the developer to correct the data causing the failure. _initializationTask = null; // Complete the task, this will throw for any requests that came in while initializing. initialization.SetException(ex); return initialization.Task; } } private static class Log { private static readonly Action<ILogger, string, Exception> _matchSuccess = LoggerMessage.Define<string>( LogLevel.Debug, new EventId(1, "MatchSuccess"), "Request matched endpoint '{EndpointName}'"); private static readonly Action<ILogger, Exception> _matchFailure = LoggerMessage.Define( LogLevel.Debug, new EventId(2, "MatchFailure"), "Request did not match any endpoints"); private static readonly Action<ILogger, string, Exception> _matchingSkipped = LoggerMessage.Define<string>( LogLevel.Debug, new EventId(3, "MatchingSkipped"), "Endpoint '{EndpointName}' already set, skipping route matching."); public static void MatchSuccess(ILogger logger, Endpoint endpoint) { _matchSuccess(logger, endpoint.DisplayName, null); } public static void MatchFailure(ILogger logger) { _matchFailure(logger, null); } public static void MatchSkipped(ILogger logger, Endpoint endpoint) { _matchingSkipped(logger, endpoint.DisplayName, null); } } }
咱们从它的源码中能够看到,EndpointRoutingMiddleware
中间件先是建立matcher
,而后调用matcher.MatchAsync(httpContext)
去寻找Endpoint,最后经过httpContext.GetEndpoint()
验证了是否已经匹配到了正确的Endpoint
并交个下个中间件继续执行!ide
app.UseEndpoints()
源代码public static IApplicationBuilder UseEndpoints(this IApplicationBuilder builder, Action<IEndpointRouteBuilder> configure) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configure == null) { throw new ArgumentNullException(nameof(configure)); } VerifyRoutingServicesAreRegistered(builder); VerifyEndpointRoutingMiddlewareIsRegistered(builder, out var endpointRouteBuilder); configure(endpointRouteBuilder); // Yes, this mutates an IOptions. We're registering data sources in a global collection which // can be used for discovery of endpoints or URL generation. // // Each middleware gets its own collection of data sources, and all of those data sources also // get added to a global collection. var routeOptions = builder.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>(); foreach (var dataSource in endpointRouteBuilder.DataSources) { routeOptions.Value.EndpointDataSources.Add(dataSource); } return builder.UseMiddleware<EndpointMiddleware>(); } internal class DefaultEndpointRouteBuilder : IEndpointRouteBuilder { public DefaultEndpointRouteBuilder(IApplicationBuilder applicationBuilder) { ApplicationBuilder = applicationBuilder ?? throw new ArgumentNullException(nameof(applicationBuilder)); DataSources = new List<EndpointDataSource>(); } public IApplicationBuilder ApplicationBuilder { get; } public IApplicationBuilder CreateApplicationBuilder() => ApplicationBuilder.New(); public ICollection<EndpointDataSource> DataSources { get; } public IServiceProvider ServiceProvider => ApplicationBuilder.ApplicationServices; }
代码中构建了DefaultEndpointRouteBuilder
终结点路由构建者对象,该对象中存储了Endpoint
的集合数据;同时把终结者路由集合数据存储在了routeOptions
中,并注册了EndpointMiddleware
中间件到http管道中;
Endpoint
对象代码以下:测试
/// <summary> /// Represents a logical endpoint in an application. /// </summary> public class Endpoint { /// <summary> /// Creates a new instance of <see cref="Endpoint"/>. /// </summary> /// <param name="requestDelegate">The delegate used to process requests for the endpoint.</param> /// <param name="metadata"> /// The endpoint <see cref="EndpointMetadataCollection"/>. May be null. /// </param> /// <param name="displayName"> /// The informational display name of the endpoint. May be null. /// </param> public Endpoint( RequestDelegate requestDelegate, EndpointMetadataCollection metadata, string displayName) { // All are allowed to be null RequestDelegate = requestDelegate; Metadata = metadata ?? EndpointMetadataCollection.Empty; DisplayName = displayName; } /// <summary> /// Gets the informational display name of this endpoint. /// </summary> public string DisplayName { get; } /// <summary> /// Gets the collection of metadata associated with this endpoint. /// </summary> public EndpointMetadataCollection Metadata { get; } /// <summary> /// Gets the delegate used to process requests for the endpoint. /// </summary> public RequestDelegate RequestDelegate { get; } public override string ToString() => DisplayName ?? base.ToString(); }
Endpoint
对象代码中有两个关键类型属性分别是EndpointMetadataCollection
类型和RequestDelegate
:ui
Controller
和Action
相关的元素集合,包含Action
上的Attribute
特性数据等RequestDelegate
:存储了Action 也即委托,这里是每个Controller 的Action 方法再回过头来看看EndpointMiddleware
中间件和核心代码,EndpointMiddleware
的一大核心代码主要是执行Endpoint 的RequestDelegate
委托,也即Controller
中的Action
的执行。this
public Task Invoke(HttpContext httpContext) { var endpoint = httpContext.GetEndpoint(); if (endpoint?.RequestDelegate != null) { if (!_routeOptions.SuppressCheckForUnhandledSecurityMetadata) { if (endpoint.Metadata.GetMetadata<IAuthorizeData>() != null && !httpContext.Items.ContainsKey(AuthorizationMiddlewareInvokedKey)) { ThrowMissingAuthMiddlewareException(endpoint); } if (endpoint.Metadata.GetMetadata<ICorsMetadata>() != null && !httpContext.Items.ContainsKey(CorsMiddlewareInvokedKey)) { ThrowMissingCorsMiddlewareException(endpoint); } } Log.ExecutingEndpoint(_logger, endpoint); try { var requestTask = endpoint.RequestDelegate(httpContext); if (!requestTask.IsCompletedSuccessfully) { return AwaitRequestTask(endpoint, requestTask, _logger); } } catch (Exception exception) { Log.ExecutedEndpoint(_logger, endpoint); return Task.FromException(exception); } Log.ExecutedEndpoint(_logger, endpoint); return Task.CompletedTask; } return _next(httpContext); static async Task AwaitRequestTask(Endpoint endpoint, Task requestTask, ILogger logger) { try { await requestTask; } finally { Log.ExecutedEndpoint(logger, endpoint); } } }
Controller
的Action
的呢?答:程序启动的时候会把全部的Controller 中的Action 映射存储到routeOptions
的集合中,Action 映射成Endpoint
终结者 的RequestDelegate
委托属性,最后经过UseEndPoints
添加EndpointMiddleware
中间件进行执行,同时这个中间件中的Endpoint
终结者路由已是经过Rouing
匹配后的路由。
EndPoint
跟普通路由又存在着什么样的关系?答:Ednpoint
终结者路由是普通路由map 转换后的委托路由,里面包含了路由方法的全部元素信息EndpointMetadataCollection
和RequestDelegate
委托。
UseRouing()
、UseAuthorization()
、UseEndpoints()
这三个中间件的关系是什么呢?答:UseRouing
中间件主要是路由匹配,找到匹配的终结者路由Endpoint
;UseEndpoints
中间件主要针对UseRouing
中间件匹配到的路由进行 委托方法的执行等操做。
UseAuthorization
中间件主要针对 UseRouing
中间件中匹配到的路由进行拦截 作受权验证操做等,经过则执行下一个中间件UseEndpoints()
,具体的关系能够看下面的流程图:
上面流程图中省略了一些部分,主要是把UseRouing 、UseAuthorization 、UseEndpoint 这三个中间件的关系突显出来。
若是您觉的不错,请微信扫码关注 【dotNET 博士】公众号,后续给您带来更精彩的分享
以上若是有错误得地方,请你们积极纠正,谢谢你们得支持!!