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 an id 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 ...