0
如果我在ASP.NET MVC Core应用程序中同时具有基于约定和基于属性的路由,如果两者匹配,哪种类型的路线优先?ASP.NET MVC Core中优先级约定与基于属性的路由
如果我在ASP.NET MVC Core应用程序中同时具有基于约定和基于属性的路由,如果两者匹配,哪种类型的路线优先?ASP.NET MVC Core中优先级约定与基于属性的路由
简而言之:基于属性的路由优先。
例子:
如你没有提供任何例子这里我可以更好地解释。
这里就是我在app.UseMvc
控制器是这样的配置。
[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());
}
}
现在你可以看到,我在属性路径,它必须除外编号更大的价值或等于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核心源代码看到下面的文件。
在UseMvc的扩展方法的一个,你会发现下面的行。
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));