liveBook · Manning

RouteAttribute

As explained in ASP.NET Core in Action, 3e

RouteAttribute is an ASP.NET Core attribute that associates a controller action with a route template.

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:

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains literal segments, parameters, multiple templates, controller prefixes, absolute routes, and HTTP-verb constraints.
Examples
Uses HomeController, CarController, appointment endpoints, multiple URLs, route parameters, and shared api/car prefixes.
What you can do after
Apply it via ASP.NET Core attributes to build explicit API URLs and constrain actions to required HTTP verbs.
How it connects
Connects attribute routing with route templates, controller actions, HTTP verbs, inherited attributes, and ApiController conventions.

Also explained in

Compare how 3 books explain RouteAttribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.