liveBook · Manning

RouteAttribute

As explained in Pro ASP.NET Core 7, Tenth Edition

The Route attribute declares URL route information on an ASP.NET Core controller or action.

`RouteAttribute` declares a controller’s base URL in ASP.NET Core MVC. Put `[Route("api/[controller]")]` on `ProductsController`: the `[controller]` token drops the `Controller` suffix, producing `/api/products`. section 19.4.2

Action attributes combine an HTTP method with that base URL. `[HttpGet]` matches GET `/api/products`; `[HttpGet("{id}")]` matches GET `/api/products/{id}`. For web-service controllers, these attributes and route patterns—not action method names—determine which requests actions handle. section 19.4.2

Listing 19.6 The contents of the ProductsController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;

namespace WebApp.Controllers {

   [Route("api/[controller]")]
   public class ProductsController : ControllerBase {
       
       [HttpGet]
       public IEnumerable<Product> GetProducts() {
           return new Product[] {
               new Product() { Name = "Product #1" },
               new Product() { Name = "Product #2" },
           };
       }
               
       [HttpGet("{id}")]
       public Product GetProduct() {
           return new Product() {
               ProductId = 1, Name = "Test Product"
           };
       }
   }
}

The controller listing shows the class-level route alongside both GET actions. section 19.4.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains controller-token substitution and composition with action routes, but does not detail routing internals.
Examples
Uses a ProductsController with GET routes for `/api/products` and `/api/products/{id}`.
What it assumes
Assumes familiarity with C# controller classes and HTTP requests while explaining the `[controller]` token.
What you can do after
Apply it via ASP.NET Core MVC to give a controller a base URL and distinguish GET endpoints.
How it connects
Connects controller routing to HTTP method attributes, action methods, and URL patterns.

Also explained in

Compare how 3 books explain RouteAttribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.