D.R.
D.R.

Reputation: 21194

Precedence convention- vs. attribute-based routing in ASP.NET MVC Core

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

Answers (1)

dotnetstep
dotnetstep

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.

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

In one of extension method of UseMvc you will find following line.

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

Upvotes: 2

Related Questions