Attribute Routing in Asp.net MVC Example

Attribute based routing in MVC Core. In this tutorial you learn attribute routing, what is attribute routing? How it works! What problem does it solve etc.

Attribute Routing in Asp.net Core

We have already explained routing concept in our earlier tutorial, if you very new to routing concept then please read routing in asp.net mvc first. Attribute routing is conceptually same but technically implemented differently; you can alternative approach to conventional routing.

Why Attribute Routing Useful?

In earlier version Asp.net MVC we had a limitation of defining SEO friendly Action Name, for example if we can have action name as "attribute-routing" instead of "attributerouting" that would be more appropriate for SEO.

How to Use Attribute Routing

Applying routing to any action using attribute is very simple!
Create a controller and an action, and then apply the attribute with any SEO friendly name you want, notice how we have applied [Route("attribute-routing")] in below IActionResult

[Route("attribute-routing")]
public IActionResult attributerouting()
{
    return View();
}

Now probably you need to make one more changes in your Configure method of Startup.cs file.
So open the startup file and make the following changes

Instead of
    app.UseMvcWithDefaultRoute();
Replace with following code
app.UseMvc(routes =>
{
   routes.MapRoute(
    name:"default", 
    template: "{controller=Home}/{action=Index}/{id?}");
});

Now you have successfully implemented Attribute Routing.
You can try accessing the page on browser by calling the attribute value, like in this case controlloerName/attribute-routing

This Routing feature was not available in earlier version of Asp.net Framework. Attribute routing allows us to create more seo friendly url very easily without making any changes in route config file, so we can make every action name more readable and seo friendly.

You also may be interested to read Asp.net MVC Routing.


Asp.Net Core C# Examples | Join Asp.Net MVC Course