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.

  1. 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) 
  1. 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) 
  1. Now, let's add RoutePrefix. This attribute will be applied to every action of this controller:
[Route("Products")] public class ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.