Creating a route using attribute routing
In this recipe, we will learn how to create a route using attribute routing.
Getting ready
We create a controller with an action
method to decorate it with routing attributes.
How to do it...
Attribute routing is the ability to define a route by adding an attribute defining a route above an action
method in a controller.
- First, let's add a routing attribute to an
action
method specifying anid
parameter:
//Route: /Laptop/10 [Route("Products/{id}")] public ActionResult Details(int id)
- Next, let's add an optional parameter:
//Route: /Products/10/Computers or /Products/10 [Route("Products/{id}/{category?}")] public ActionResult Details(int id, string category) We can see how to do that for a RESTfull Web API method : // GET api/values/5 [HttpGet("{id?}")] public string Get(int? id)
- Now, let's addÂ
RoutePrefix
. This attribute will be applied to every action of this controller:
[Route("Products")] public class HomeController : Controller...