What is Attribute Routing in MVC?

Category: C SharpWhat is Attribute Routing in MVC?
Editor">Editor Staff asked 2 years ago

What is Attribute Routing in MVC?

1 Answers
Editor">Editor Staff answered 2 years ago

A route attribute is defined on top of an action method. The following is the example of a Route Attribute in which routing is defined where the action method is defined.
 
In the following example, I am defining the route attribute on top of the action method

 

  1. public class HomeController: Controller  
  2. {  
  3.     //URL: /Mvctest  
  4.     [Route(“Mvctest”)]  
  5.     public ActionResult Index()  
  6.     ViewBag.Message = “Welcome to ASP.NET MVC!”;  
  7.     return View();  
  8. }  
  9. }  

Attribute Routing with Optional Parameter
 
We can also define an optional parameter in the URL pattern by defining a mark (“?”) to the route parameter. We can also define the default value by using parameter=value. 

 

  1. public class HomeController: Controller   
  2. {  
  3.         // Optional URI Parameter  
  4.         // URL: /Mvctest/  
  5.         // URL: /Mvctest/0023654  
  6.         [Route(“Mvctest /  
  7.         {  
  8.             customerName ?  
  9.         }”)]  
  10.         public ActionResult OtherTest(string customerName)  
  11.         ViewBag.Message = “Welcome to ASP.NET MVC!”;  
  12.         return View();  
  13.     }  
  14.     // Optional URI Parameter with default value  
  15.     // URL: /Mvctest/  
  16.     // URL: /Mvctest/0023654  
  17.     [Route(“Mvctest /   
  18.     {  
  19.         customerName = 0036952  
  20.     }”)]  
  21. public ActionResult OtherTest(string customerName)  
  22. {  
  23.     ViewBag.Message = “Welcome to ASP.NET MVC!”;  
  24.     return View();  
  25. }  
  26. }