Learn Attribute Routing in ASP.NET Core

Learn Attribute Routing in ASP.NET Core

The concept of Routing is very vast and I have covered it in 6 tutorials which are:

So make sure you cover each of these one by one.

So far what you have seen is Convention Routing. There is another technique of routing which is known by the name of Attribute Routing. In Attribute Routing you apply route as C# attributes directly to the controller and actions.

Example

Let’s take a simple example first. Apply the attribute – [Route("CallRoute")] to the Home Controller’s Index Action method so that it looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace URLRouting.Controllers
{
    public class HomeController : Controller
    {
        [Route("CallRoute")]
        public IActionResult Index()
        {
            return View();
        }

        // other actions
    }
}

Remove all the Routes from the Startup.cs class except the default one:

app.UseEndpoints(endpoints =>
{
    // Default route
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

Now run your application and go to the URL – https://localhost:58470/CallRoute. You will see the Index action method of the Home controller is invoked.

You will also note that your previous URL of this Index action – https://localhost:58470/Home/Index & https://localhost:58470 no longer works as it prevents the routes from Convention Routing to be applied.

Just like Attribute Routes Filters are attributes applied to controllers or actions. Filters perform custom logic to execute before or after action method. Refer – Learn to use Filters in ASP.NET core from beginning to expert level

However other action routes from Convention routing like – https://localhost:58470/Home/Check/Ram will continue to work. So that means – If there is an Attribute Routing applied to a Controller or an Action then the Convention Routes for the Controller or Action will not work.

The ‘controller’ & ‘action’ terms in Attribute Routing

The [controller] and [action] terms are used to reference the Controller and Action names, just like in Convention Routing. To understand it create a new Controller and name it AdminController.cs. Add the following code to this controller:

using Microsoft.AspNetCore.Mvc;
namespace URLRouting.Controllers
{
    public class AdminController : Controller
    {
        [Route("[controller]/CallMe")]
        public string Index()
        {
            return "'Admin' Controller, 'Index' View";
        }
 
        public string List()
        {
            return "'Admin' Controller, 'List' View";
        }
    }
}

You can see that I applied the Attribute Route to the Index action method. This route has the term called controller which states that the URL should have the Controller segment in it.

So to invoke the Index method you have to go to the URL – https://localhost:58470/Admin/Callme.

Related tutorial – Model Binding in ASP.NET Core

Note that since there is no Attribute Routes applied to the List action so its URL will be formed by the Convention Routing, and they will be https://localhost:58470/Admin/List.

To see how the Action Name is applied, add another action method called Show to the AdminController.cs file with attribute routing as shown below:

[Route("[controller]/CallMe/[action]")]
public string Show()
{
    return "'Admin' Controller, 'Show' View";
}

To invoke this action the URL will be – https://localhost:58470/Admin/CallMe/Show

Attribute Routing applied on the Controller

You can also apply attribute routing on the Controller. This will make all it’s action method inherit it that is the attribute route will apply on them. So change the code of the Admin Controller as shown below:

using Microsoft.AspNetCore.Mvc;
 
namespace URLRouting.Controllers
{
    [Route("News/[controller]/USA/[action]/{id?}")]
    public class AdminController : Controller
    {
        public string Index()
        {
            return "'Admin' Controller, 'Index' View";
        }
 
        public string List(string id)
        {
            return "'Admin' Controller, 'List' View";
        }
 
    }
}

The Attribute Routing is applied to the Admin controller so both its action method inherit it.

Here the URLs to invoke Index action will be:

1. /News/Admin/USA/Index
2. /News/Admin/USA/Index/100
3. /News/Admin/USA/Index/Hello

And the URLs to invoke List action will be:

1. /News/Admin/USA/List
2. /News/Admin/USA/List/100
3. /News/Admin/USA/List/Hello

Route Constraint in Attribute Routing

Route Constraint can be applied to the Attribute Routing. I had created a Custom Constraint called OnlyGodsConstraint on my last tutorial. It can be applied to the attribute routing as well – just like what I did in the below highlighted code of the Admin controller:

using Microsoft.AspNetCore.Mvc;
 
namespace URLRouting.Controllers
{
    [Route("News/[controller]/USA/[action]/{id:allowedgods?}")]
    public class AdminController : Controller
    {
        public string Index()
        {
            return "'Admin' Controller, 'Index' View";
        }
 
        public string List(string id)
        {
            return "'Admin' Controller, 'List' View";
        }
 
    }
}

So the URL to invoke the Index method will become – https://localhost:58470/News/Admin/USA/Index/Shiv. See the below image:

attribute routing constraint

You can download the full codes of this tutorial from the below link:

Download

Conclusion

In this tutorial you learned to use Attribute-Based Routing. I hoped you liked this tutorial. Check the next tutorial whose link is given below.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.