Jorge Filipe Pinto
Jorge Filipe Pinto

Reputation: 65

What's the difference between configuration-based routing and attribute routing in MVC?

I have used the most conventional way to build routes:

        routes.MapRoute(
            name: "Client",
            url: "{controller}/{id}",
            defaults: new { controller = "Client", action = "Index", id = UrlParameter.Optional });


        routes.MapRoute(
            "Default,
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

But I have trouble in some routes, and I came across a new way to create routes in MVC 5.

The next example:

public class ClientController : BaseController
{
    [HttpGet]
    [Route"({controller}/{id})"]
    public ActionResult Index(string id = null)        
    {
    }        

    [Route"({controller}/{action}/{id})"]
    public ActionResult GetAllClients(string id = null)        
    {
    }
}

I wonder if it works well , and what is the real difference between them. Someone can help me?

Upvotes: 0

Views: 487

Answers (1)

mason
mason

Reputation: 32694

Your first example is the configuration-based routing system, where you are handed a route builder and add your routes to it. This centralizes your route configuration code.

The second example is known as attribute routing. It allows you to specify the routes by applying attributes to controllers and action method.

They both still function. It comes down to a choice as to how you'd like to organize your code. And that's opinion based, so I will not delve into that discussion. Test both of them, and pick the one that you like best.

Note, these are not the only two options for routing. For example, SharpRouting adds functions to each controller to be called that create the routes through a fluent API. There are probably other options out there, or you can create your own!

For more information about routing in ASP.NET, see Microsoft's documentation.

Full disclaimer I work with the developer that created SharpRouting and we use it in our software (it may have been originally developed for our application, I'm not sure).

Upvotes: 1

Related Questions