搁置了几天,工作忙的一塌糊涂,今天终于抽空来继续看看MVC的知识。先来看看MVC的路由是如何处理的。以下为替代的路由:
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default",pattern: {controller=Home}/{action=Index}/{id?}); });
UseEndpoints:将中间件添加到的IApplicationBuilder再调用该方法时,需要先调用UseRouting。
public static IApplicationBuilder UseRouting(this IApplicationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } VerifyRoutingServicesAreRegistered(builder);//校验是否加载完成 var endpointRouteBuilder = DefaultEndpointRouteBuilder(builder); builder.Properties[EndpointRouteBuilder] = endpointRouteBuilder; return builder.UseMiddleware<EndpointRoutingMiddleware>(endpointRouteBuilder); }
将Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware中间件添加到指定的IApplicationBuilder中。
private static void VerifyRoutingServicesAreRegistered(IApplicationBuilder app) { Verify if AddRouting was done before calling UseEndpointRouting/UseEndpoint We use the RoutingMarkerService to make sure if all the services were added. if (app.ApplicationServices.GetService(typeof(RoutingMarkerService)) == InvalidOperationException(Resources.FormatUnableToFindServices( nameof(IServiceCollection),nameof(RoutingServiceCollectionExtensions.AddRouting),ConfigureServices(...))); }
static IApplicationBuilder UseEndpoints(this IApplicationBuilder builder,Action<IEndpointRouteBuilder> configure) { ArgumentNullException(nameof(builder)); } if (configure == 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>(); }
ASP.NET Core 3使用完善的终结点路由,通常可以对应用程序内部的路由提供更多控制。端点路由分为两个单独的步骤:
在第一步中,再次匹配所请求的路由和配置的路由,找出以访问正在的路由。在最后一步中,对确定的路由进行评估,并调用相应的中间件。
两个步骤独立,允许其他中间件在这些点之间起作用。允许中间件利用来自一个子的端点路由信息来处理授权,而不必执行实际的处理程序。
app.UseRouting()将注册运行逻辑路由路由的中间件。
app.UseEndpoints()将执行该路由。
MapControllerRoute:添加端点控制器操作的IEndpointRouteBuilder 并指定与路由给定name
,pattern
, defaults
,constraints
,和dataTokens
。
其他:
MapControllerRoute 添加控制器的常规路由
原创。转载请注明出处。