Attribute Routing With ASP.net MVC 5
Introduction
- This Article shows how to use the Latest ASP.net MVC 5 Attribute Routing with your Application.
- This Article has 2 parts.First part of this Article will show the basic usage of Attribute Routing.
- Now you can read the 2nd part of this Article here 'Attribute Routing With ASP.net MVC 5 - Route Constraints'
What is Routing ?
- Routing is how ASP.net MVC matches a URI to an Action
What is Attribute Routing ?
- ASP.net MVC 5 supports a new type of Routing, called Attribute Routing
- As the name implies, attribute routing uses attributes to define routes
- Attribute routing gives you more control over the URIs in your web application
How To Enable Attribute Routing ?
- For that, You have to select the RouteConfig.cs inside the App_Start Folder.
- After that call MapMvcAttributeRoutes is as below.
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); //Attribute Routing
//Convention-based Routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
}
}
Key points of the above code
- To enable Attribute Routing,You have to call MapMvcAttributeRouteson RouteConfig File.
- If you want, You can keep the Convention-based Routing also with the same file is as above.
- But routes.MapMvcAttributeRoutes(); Should configure before the Convention-based Routing.
How to use Optional URI Parameters ?
- To that you can add a question mark to the Route parameter
- Well, It's like this : [Route("Pet/{petKey?}")]
PetController.cs
{
// eg: /Pet
// eg: /Pet/123
[Route("Pet/{petKey?}")]
public ActionResult GetPet(string petKey)
{
return View();
}
}
Key point of the above code
- In the above example, both /Pet and /Pet/123 will Route to the “GetPet” Action
Above Route on Browser is as below
How to use Default Values URI Parameters ?
- To that you can specify a default value to the route parameter
- It's like this : [Route("Pet/Breed/{petKey=123}")]
PetController.cs
public class PetController : Controller
{
// eg: /Pet/Breed
// eg: /Pet/Breed/528
[Route("Pet/Breed/{petKey=123}")]
public ActionResult GetSpecificPet(string petKey)
{
return View();
}
}
Key point of the above code
- In the above example, both /Pet/Breed and /Pet/Breed/528 will route to the“GetSpecificPet” Action
How to use Route Prefixes ?
- Normally, the routes in a controller all start with the same prefix
- Well,It's like this : /Booking
BookingController.cs
public class BookingController : Controller
{
// eg: /Booking
[Route("Booking")]
public ActionResult Index() { return View(); }
// eg: /Booking/5
[Route("Booking/{bookId}")]
public ActionResult Show(int bookId) { return View(); }
// eg: /Booking/5/Edit
[Route("Booking/{bookId}/Edit")]
public ActionResult Edit(int bookId) { return View(); }
}
No comments:
Post a Comment