Attribute routing in MVC is used to call your Web API methods.
You can define the route and their prefixes so that whenever these API are called you can call it with your defined name.
You can bind the route according to your need by the use of this attribute routing concept.

Controller level attribute routing
In controller level attribute routing we can define the route and action associated to it.
We use the controllers to define all these things
[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();
}
}
Action level attribute routing
In this you have to define the routing to the action being performed but not over the controller. It is applied to the particular action of 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();
}
}
0 Comment(s)