RouteAttribute maps a URL route template to an action method in an ASP.NET Core web API controller. The template, not the controller or action name, determines which URL invokes the method. section 20.3
Mapping actions to URLs
A controller can map the root URL and a contact URL directly: [Route("")] maps / to Index, while [Route("contact")] maps /contact to Contact. One action can also have multiple RouteAttribute declarations, such as /car/start, /car/ignition, and /start-car for Start.
Use route templates to control the URL shape:
- Add literal segments such as car/speed. section 20.3
RouteAttribute responds to all HTTP verbs. For verb-specific endpoints, use HttpGet, HttpPost, HttpPut, or related attributes with the route template; a matching URL with the wrong verb produces 405 Method Not Allowed. section 20.3.3
Listing 20.7 Combining RouteAttribute templates
[Route("api/car")]
public class CarController
{
[Route("start")] #1
[Route("ignition")] #2
[Route("/start-car")] #3
public IActionResult Start()
{
/* method implementation*/
}
[Route("speed/{speed}")] #4
[Route("/set-speed/{speed}")] #5
public IActionResult SetCarSpeed(int speed)
{
/* method implementation*/
}
}
#1 Combines to give “api/car/start”
#2 Combines to give “api/car/ignition”
#3 Does not combine because it starts with /; gives the “start-car” template
#4 Combines to give “api/car/speed/{speed}”
#5 Does not combine because it starts with /; gives the “set-speed/{speed}” template
Inspect how controller and action RouteAttribute templates combine, and how a leading slash creates an independent route. section 20.3.1


