擱置了幾天,工作忙的一塌糊塗,今天終於抽空來繼續看看MVC的知識。先來看看MVC的路由是如何處理的。以下為替代的路由: app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{ ...
擱置了幾天,工作忙的一塌糊塗,今天終於抽空來繼續看看MVC的知識。先來看看MVC的路由是如何處理的。以下為替代的路由:
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
通過Configure方法在運行時,以委托的形式註冊。
UseEndpoints:將中間件添加到的IApplicationBuilder再調用該方法時,需要先調用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); }
將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)) == null) { throw new InvalidOperationException(Resources.FormatUnableToFindServices( nameof(IServiceCollection), nameof(RoutingServiceCollectionExtensions.AddRouting), "ConfigureServices(...)")); }
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>(); }
ASP.NET Core 3使用完善的終結點路由,通常可以對應用程式內部的路由提供更多控制。端點路由分為兩個單獨的步驟:
在第一步中,再次匹配所請求的路由和配置的路由,找出以訪問正在的路由。在最後一步中,對確定的路由進行評估,並調用相應的中間件。
兩個步驟獨立,允許其他中間件在這些點之間起作用。允許中間件利用來自一個子的端點路由信息來處理授權,而不必執行實際的處理程式。
app.UseRouting()將註冊運行邏輯路由路由的中間件。
app.UseEndpoints()將執行該路由。
MapControllerRoute:添加端點控制器操作的IEndpointRouteBuilder 並指定與路由給定name
,pattern
, defaults
,constraints
,和dataTokens
。
其他:
MapController將添加到屬性路由的控制器支持。
MapController將添加到該屬性路由的控制器支持。
MapControllerRoute 添加控制器的常規路由
原創。轉載請註明出處。
啰嗦一堆,就說了兩個方法,下一篇接著說路由的用法〜