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 ==  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(...).;
         InvalidOperationException(message);
    }
    创建默认mvc处理类 
    RouteBuilder为RouterMiddleware中间件创建所需的Router对象
    var routes =  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());
}
interface IRouteBuilder
{
    获取applictionbuilder  (将中间件委托添加到应用程序的请求管道)
    IApplicationBuilder ApplicationBuilder { get; }
    获取路由(核心)
    IRouter DefaultHandler { get; set获取IServiceProvider用来解析路由服务的集合
    IServiceProvider ServiceProvider { 获取路由集合
    IList<IRouter> Routes { ; }
    IRouter Build();
}
主要是用来处理 RouteAttribute 标记的Action,
static IRouter CreateAttributeMegaRoute(IServiceProvider services)
{
    if (services ==  ArgumentNullException(nameof(services));
    }
    return  AttributeRoute(
        services.GetRequiredService<IActionDescriptorCollectionProvider>
        {
            var handler = services.GetRequiredService<MvcAttributeRouteHandler>();
            handler.Actions = actions;
             handler;
        });
}

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

 原创,转载注明出处。
 

 

 

 

相关文章

本文将从上往下,循序渐进的介绍一系列相关.NET的概念,先从...
基于 .NET 的一个全新的、好用的 PHP SDK + Runtime: Pe...
.NET 异步工作原理介绍。
引子 .NET 6 开始初步引入 PGO。PGO 即 Profile Guided Opti...
前言 2021/4/8 .NET 6 Preview 3 发布,这个版本的改进大多来...
前言 开头防杠:.NET 的基础库、语言、运行时团队从来都是相...