Reputation: 21194
If I have both, convention- and attribute-based routing in an ASP.NET MVC Core application. Which type of route is taking precedence if both would match?
Upvotes: 0
Views: 843
Reputation: 17485
In short answer : Attribute based route take precedence.
Example :
As you have not provided any example here what I can best explain.
Here what I configured in 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?}");
});
Controller look like this.
[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());
}
}
Now you can see that I have applied constraint in attribute route that it must except value of Id greater or equal to 20. Same configuration is not present for convention based route.
Now in browser ( By This example it will
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.
Now you know why as Attribute based route added first then other route added so.
In Github asp.net core source see following file.
In one of extension method of UseMvc you will find following line.
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
Upvotes: 2