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;
        });
}

先写道在这里,虽然用到了它的方法过一遍,但还是对整个路由的流转方式不是太清楚,所以我们下一篇将详细说明以下路由的管道流转过程。

 原创,转载注明出处。
 

 

 

 

posted @ 2020-02-22 01:21  温暖如太阳  阅读(2242)  评论(0编辑  收藏  举报