Join Class

Attribute routing in core example

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

We have already explained routing concept in our earlier tutorial, if you very new to routing concept then please read routing in 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 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.

Use Attribute Routing in core

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

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
Replace with following code
app.UseMvc(routes =>
    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 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 MVC Routing. Core Course
Attribute Routing Example in Core MVC Core Tutorial for Beginners
ASP.NET MVC Interview Questions Answers
Hire .Net Developer
Asp.Net Core C# Examples | Join Asp.Net MVC Course