微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

 原创,转载注明出处。
 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐