What is Attribute Routing and how to define it?

ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

  1. Controller level routing – You can define routes at controller level which apply to all actions within the controller unless a specific route is added to an action.
    [RoutePrefix("MyHome")][Route("{action=index}")] //default action
    public class HomeController: Controller { //new route: /MyHome/Index
    	public ActionResult Index() {
    		return View();
    	} //new route: /MyHome/About
    	public ActionResult About() {
    		ViewBag.Message = "Your application description page.";
    		return View();
    	} //new route: /MyHome/Contact
    	public ActionResult Contact() {
    		ViewBag.Message = "Your contact page.";
    		return View();
    	}
    }
  2. Action level routing – You can define routes at action level which apply to a specific action with in the controller.
    public class HomeController: Controller {
    	[Route("users/{id:int:min(100)}")] //route: /users/100
    	public ActionResult Index(int id) { //TO DO:
    		return View();
    	}[Route("users/about")] //route" /users/about
    	public ActionResult About() {
    		ViewBag.Message = "Your application description page.";
    		return View();
    	} //route: /Home/Contact
    	public ActionResult Contact() {
    		ViewBag.Message = "Your contact page.";
    		return View();
    	}
    }

Note:

  • Attribute routing should configure before the convention-based routing.
  • When you combine attribute routing with convention-based routing, actions which do not have Route attribute for defining attribute-based routing will work according to convention-based routing. In above example Contact action will work according to convention-based routing.
  • When you have only attribute routing, actions which do not have Route attribute for defining attribute-based routing will not be the part of attribute routing. In this way they can’t be access from outside as a URI.
Tagged , . Bookmark the permalink.

Leave a Reply