liveBook · Manning

RouteAttribute

As explained in Building Web APIs with ASP.NET Core

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

RouteAttribute associates a controller or action with a route template. Applied to a controller, it establishes a routing prefix shared by that controller’s actions, such as [Route("api/[controller]")]. section 1.2.3

Use the attribute to shape controller URLs:

  • Place [Route("api/[controller]")] on a controller to create a centralized /api/Sample/ prefix for a SampleController. section 1.2.3
  • Combine the controller route with action attributes such as [HttpGet] and [HttpDelete] to map HTTP operations and parameters. section 1.2.3
  • Choose [Route("[controller]")] when a controller should follow the routing pattern used by BoardGamesController rather than the api/ prefix. section 5.3.4

SeedController route

A SeedController can use [Route("[controller]")] above the class, alongside [ApiController]. Its route pattern is therefore based on the controller name, while its constructor handles services such as ApplicationDbContext and ILogger through dependency injection. section 5.3.4

[ApiController]                                #1
[Route("api/[controller]")]                    #2
public class SampleController : ControllerBase
{
    public SampleController()
    {
    }
 
    [HttpGet]                                  #3
    public string Get()
    {
        return "TODO: return all items";
    }
 
    [HttpGet("{id}")]                          #4
    public string Get(int id)
    {
        return $"TODO: return the item with id #{id}";
    }
 
    [HttpDelete("{id}")]                       #5
    public string Delete(int id)
    {
        return $"TODO: delete the item with id #{id}";
    }
}

Inspect the complete controller example showing the route attribute, HTTP verb attributes, route parameters, and ControllerBase inheritance together. section 1.2.3

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains controller-level prefixes and route-template choices, while deferring broader API status-code conventions.
Examples
Uses SampleController routes for collection, identifier, and delete requests, plus SeedController’s [controller] route.
What it assumes
Assumes familiarity with ASP.NET Core controllers and introduces routing through concrete controller and action declarations.
What you can do after
Configure controller URL patterns and combine them with HTTP verb attributes to expose API actions.
How it connects
Connects controllers with action methods, HTTP verbs, route parameters, ControllerBase, ApiController, and app.MapControllers().

Also explained in

Compare how 3 books explain RouteAttribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.