Attribute Routing in MVC
Dec 09, 2020 07:37 0 Comments MVC PARTH

                  Attribute Routing in MVC

When we are using the [Route] attribute to define routes, it is called Attribute Routing. It provides us more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application.

How to use Attribute Routing:

Follow below steps to use attribute routing -

  1. First of all, enable the Attribute Routing in ASP.NET MVC Application for which we just need to add a call to routes.MapMvcAttributeRoutes() method within our RegisterRoutes() method of our RouteConfig.cs file.

Example –

namespace AttributeRouting


    public class RouteConfig


        public static void RegisterRoutes(RouteCollection routes)



            //Enabling attribute routing



                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }





     2. The next step is to decorate the action method with the Route attribute.

Example –



public ActionResult GetEmployeeData(int employeeID)


    List WorkList = new List();

    if (employeeID == 123456)

        WorkList = new List() { "Design", "Development” };

    else if (employeeID == 234567)

        WorkList = new List() { "Design", "Development”, “Testing” };

    else if (employeeID == 345678)

        WorkList = new List() { "Design", "Development”, “Testing”, “Deployment” };


        WorkList = new List() { "Design", "Development”, “Testing”, “Deployment”, “Sign Off” };

    ViewBag.WorkList = WorkList;

    return View();



Advantages of using Attribute Routing :

  1. It helps developer in the debugging by providing information about routes.
  2. It also reduces the chances for errors, because if a route is modified incorrectly in RouteConfig. cs then it may affect the entire application's routing which is not the case with attribute routing.


Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.

Let`s Connect