【问题标题】:Precedence convention- vs. attribute-based routing in ASP.NET MVC Core优先约定 - 与 ASP.NET MVC Core 中基于属性的路由
【发布时间】:2016-11-19 16:22:52
【问题描述】:

如果我在 ASP.NET MVC Core 应用程序中同时拥有基于约定和基于属性的路由。如果两者都匹配,哪种类型的路由优先?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    简而言之:基于属性的路由优先。

    例子:

    因为你没有在这里提供任何我能最好解释的例子。

    这是我在 app.UseMvc 中配置的内容

        app.UseMvc(routes =>
            {
                routes.MapRoute(
                   name: "default1",
                   template: "{controller=My}/{action=Index}/{id:int}");   // This route I added for your question clarification.
    
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
    

    控制器看起来像这样。

    [Route("My")]  // Disable this line if attribute route need to be disable.
    public class MyController : Controller
    {
        [Route("Index/{id:min(20)}")] // Disable this line if attribute route need to be disable.
        // GET: /<controller>/
        public IActionResult Index(int id)
        {            
            return Content("This is just test : " + id.ToString());
        }        
    }
    

    现在你可以看到我在属性路由中应用了约束,它必须除了 Id 的值大于或等于 20。相同的配置不存在 对于基于约定的路线。

    现在在浏览器中(通过这个例子它将

    http://localhost:yourport/My/Index/1   // This will match with contention based route but will not call as attribute route will take precendence
    
    http://localhost:yourport/My/Index/21   // This will call successfully.
    

    现在您知道为什么先添加基于属性的路由,然后添加其他路由。

    在 Github asp.net 核心源码中查看以下文件。

    https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Builder/MvcApplicationBuilderExtensions.cs

    在 UseMvc 的一种扩展方法中,您将找到以下行。

    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2014-02-12
      • 2017-11-20
      • 2017-07-16
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多