DotnetProg DotnetProg - 1 month ago 10
ASP.NET (C#) Question

Attribute Based Routing VS Convention Based Routing - Best Practice for ASP.net Core RESTful APIs

I'm an experienced .NET developer, making my first steps in .NET Core in the passed few days, more specific in building RESTful APIs using ASP.net Core.

I know there are 2 possible routing options - Convention Routing (traditional) vs the Attribute Based Routing (newer).

I've read that the ASP.net core's development team recommendation is to use Attribute Based Routing for APIs rather than the tradition Convention Based routing, which is more suitable for MVC applications.

I'd really like to understand - Why?

It seems that the attribute based routing makes us write more code ending up having the same behavior as the conventional routing.

Answer Source

Both options are valid. Following are some suggestions on when to use each one. Consider choosing traditional routes when:

  • You want centralized configuration of all your routes.
  • You use custom constraint objects.
  • You have an existing working application you don't want to change

Consider choosing attribute routes when:

  • You want to keep your routes together with your action's code
  • You are creating a new application or making significant changes to an existing.
  • You want to match route parameter names with an actual parameter of the method(action), this will make the route parameter more descriptive and omit the weird error where the route ID would not match and that usually happens because we didn't configure routing correctly and we were using asp.net default route.

But the reasons why many developers recommend the Attribute Routes is because it allows you quite a bit more flexibility and places the routes next to the actions that will actually use them. You can switch from option to another at any time is not difficult