OK, I know the easiest way to use Attribute Routing in MVC 6 is:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
And here is the controller code using the new Tokens (without Areas):
[Route("[controller]/[action]")]
public class HomeController : Controller
{
}
And here is the controller code using the new Tokens (with Areas):
[Area("MyArea")]
[Route("[controller]/[action]")]
public class HomeController : Controller
{
}
Questions:
Lastly, I know I can play this game, but isn't the 1st convention-based approach - app.UseMvc() - the simplest?
public void Configure(IApplicationBuilder app)
{
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
}
MVC 5 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported.
Action selectors are attributes that can be applied to action methods and are used to influence which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request.
Microsoft gives you two options, each with own pros and cons. You should decide which one is better based on your context/needs.
Convention based routing
Pros:
Cons:
Attribute-based routing
Pros:
Cons:
How to decide which one to use:
If you have/expect to have very few routes.MapRoute()
calls -> use convention routing as its simpler
If you have/expect to have lots of routes.MapRoute()
calls -> use attribute routing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With