Asp.net Core MVC(三)UseMvc設置路由


在家辦公,下班繼續看點東西,不廢話,繼續看MVC的路由。

asp.net核心mvc的路由是建立在asp.net核心的路由之上的。通過終結點加載路由中間件的配置方式在此不細說了,(DOTNET Core MVC(二)已經說明)。在看一下其他的加載方式:

app.UseMvc(routes =>
{
  //使用指定的名稱和模板將路由添加到IRouteBuilder。
   routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

這種方式在.net core 3.0(使用終結點加載路由中間件)中使用會提示

 

 

根據提示我們在代碼中添加:

ConfigureServices方法中添加:

//不啟用終結點
services.AddMvc(options => options.EnableEndpointRouting = false);
public static IApplicationBuilder UseMvc( this IApplicationBuilder app, Action<IRouteBuilder> configureRoutes
{
    if (app == null)
    {
        throw new ArgumentNullException(nameof(app));
    }
    if (configureRoutes == null)
    {
        throw new ArgumentNullException(nameof(configureRoutes));
    }
    //在調用UseMvc之前驗證AddMvc是否已完成
    VerifyMvcIsRegistered(app);
    var options = app.ApplicationServices.GetRequiredService<IOptions<MvcOptions>>();
    if (options.Value.EnableEndpointRouting)
    {
        var message =
            "Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use " +
            "'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside " +
            "'ConfigureServices(...).";
        throw new InvalidOperationException(message);
    }
    //創建默認mvc處理類 
    //RouteBuilder為RouterMiddleware中間件創建所需的Router對象
    var routes = new RouteBuilder(app)
    {
        DefaultHandler = app.ApplicationServices.GetRequiredService<MvcRouteHandler>(),
    };
    //配置MVC路由的回調
    configureRoutes(routes);
    //CreateAttributeMegaRoute:返回一個IRouter 主要是用來處理 RouteAttribute 標記的Action,
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
    //使用制定的路由將路由中間件田間到制applicationbuilder
    return app.UseRouter(routes.Build());
}
public interface IRouteBuilder
{
    //獲取applictionbuilder  (將中間件委托添加到應用程序的請求管道)
    IApplicationBuilder ApplicationBuilder { get; }
    //獲取路由(核心)
    IRouter DefaultHandler { get; set; }
    //獲取IServiceProvider用來解析路由服務的集合
    IServiceProvider ServiceProvider { get; }
    //獲取路由集合
    IList<IRouter> Routes { get; }
    IRouter Build();
}
//主要是用來處理 RouteAttribute 標記的Action,
public static IRouter CreateAttributeMegaRoute(IServiceProvider services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }
    return new AttributeRoute(
        services.GetRequiredService<IActionDescriptorCollectionProvider>(),
        services,
        actions =>
        {
            var handler = services.GetRequiredService<MvcAttributeRouteHandler>();
            handler.Actions = actions;
            return handler;
        });
}

先寫道在這里,雖然用到了它的方法過一遍,但還是對整個路由的流轉方式不是太清楚,所以我們下一篇將詳細說明以下路由的管道流轉過程。

 原創,轉載注明出處。
 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM