ASP.NET MVC Core中的优先约定与基于属性的路由

时间:2016-11-19 16:22:52

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

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

1 个答案:

答案 0 :(得分:2)

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

示例:

由于您未在此处提供任何示例,我可以最好地解释。

这是我在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));