Routing
Conventional, attribute and endpoint routing.
Routing in ASP.NET Core
1. About
Prerequisites
- Basic C# and HTTP knowledge.
- Familiarity with
Program.csand the ASP.NET Core middleware pipeline. - Basic understanding of controllers and Minimal APIs.
Learning outcomes
By the end of this module, you will be able to explain endpoint routing, write conventional and attribute routes, use parameters and constraints, organize Minimal APIs with route groups, generate URLs, troubleshoot route failures, and apply routing security best practices.
2. Introduction
Routing is the process of matching an incoming HTTP request to the endpoint that should handle it. The route path, HTTP method, route template, constraints, and endpoint metadata help ASP.NET Core determine which handler is appropriate.
An online store might expose:
| Method | URL | Purpose |
|---|---|---|
| GET | /products | List products |
| GET | /products/42 | Get product 42 |
| POST | /products | Create a product |
| PUT | /products/42 | Replace product 42 |
| DELETE | /products/42 | Delete product 42 |
The URL path alone is not always enough; the HTTP method also matters.
Routing exists so developers don't have to manually inspect every request path and dispatch it to a handler. It supports predictable URLs, controller actions, Minimal APIs, route-value binding, link generation, and API organization.
Key idea: Routing chooses which endpoint can handle the request. Authentication identifies the caller; authorization decides whether the caller may perform the operation.
3. Real-life analogy: hospital reception
Imagine a hospital reception desk. Visitors describe the service they need, and reception directs them to the right department.
- Request URL: the requested department or service.
- HTTP method: the kind of operation requested.
- Route template: the type of request a department accepts.
- Route parameter: a patient or appointment number.
- Endpoint: the department that handles the request.
- Authorization: the check that determines whether the visitor may access a service.
Reception directs the visitor; it doesn't perform the treatment. Likewise, routing selects the endpoint but doesn't normally implement the business operation.
4. Architecture diagram
This is a logical view. In a real app, endpoint selection, middleware, and endpoint execution are integrated into the request pipeline; precise placement depends on the hosting model and configuration.
5. Concept explanation
5.1 What is an endpoint?
An endpoint is an executable request handler combined with metadata describing how it should be selected or processed. Examples include a Minimal API handler, controller action, or Razor Page endpoint.
app.MapGet("/hello", () => "Hello!");
This associates /hello with a handler that returns a response.
5.2 Endpoint routing
Modern ASP.NET Core uses endpoint routing. It separates endpoint selection from endpoint execution:
- The application registers endpoints.
- A request arrives and ASP.NET Core creates an
HttpContext. - Routing compares the request with registered route patterns and metadata.
- A matching endpoint is selected and route values are made available.
- Middleware such as authentication and authorization runs according to configuration.
- The selected endpoint executes and produces a response.
You may see UseRouting() in explicit pipelines. With modern minimal hosting, endpoint registration such as MapGet and MapControllers integrates with the hosting model. Explicit routing middleware is still useful when you need precise ordering.
5.3 Route templates
A route template describes the shape of a URL.
| Template | Example | Meaning |
|---|---|---|
/products | /products | Fixed path |
/products/{id} | /products/42 | Variable segment |
/products/{id:int} | /products/42 | Integer-constrained parameter |
/articles/{slug} | /articles/routing-basics | Captured slug |
/users/{userId}/orders/{orderId} | /users/7/orders/21 | Multiple route values |
Curly braces define route parameters. A normal parameter captures one path segment.
5.4 Route parameters
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { ProductId = id }));
For /products/42, the handler receives id = 42. ASP.NET Core binds route values to handler parameters. Explicit types and constraints make the route's intent easier to understand.
5.5 Required, optional, and default parameters
A required parameter must be present for the route to match:
app.MapGet("/categories/{categoryId:int}", (int categoryId) =>
Results.Ok(new { categoryId }));
An optional segment uses ?:
app.MapGet("/archive/{year?}", (string? year) =>
Results.Ok(new { year = year ?? "all years" }));
A conventional route can provide defaults:
app.MapControllerRoute(
name: "catalog",
pattern: "catalog/{category=all}",
defaults: new { controller = "Catalog", action = "Index" });
Avoid too many optional combinations. Use clear resource paths and query parameters for filtering when that makes the URL easier to understand.
5.6 Route constraints
Constraints restrict which values can match a route.
app.MapGet("/orders/{id:int}", (int id) =>
Results.Ok(new { OrderId = id }));
/orders/123 matches this route; /orders/abc does not match this constrained endpoint.
| Constraint | Example | Purpose |
|---|---|---|
int | {id:int} | Integer-shaped value |
long | {id:long} | Long integer |
guid | {id:guid} | GUID |
bool | {enabled:bool} | Boolean-shaped value |
alpha | {name:alpha} | Alphabetic characters |
minlength(3) | {code:minlength(3)} | Minimum string length |
maxlength(20) | {code:maxlength(20)} | Maximum string length |
length(2,10) | {code:length(2,10)} | Length range |
range(1,100) | {page:int:range(1,100)} | Numeric range |
Note: Constraints are primarily for route matching, not full business validation. If a constraint fails, the endpoint may not match and the response may be 404. Use model or application validation for business rules and useful client feedback.
5.7 HTTP methods and routing
A resource path can support multiple operations based on method:
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { id }));
app.MapDelete("/products/{id:int}", (int id) =>
Results.NoContent());
Both use the same path shape but have different HTTP method metadata. If the path is known but the method is unsupported, the app may return 405 Method Not Allowed, depending on endpoint registration and fallback behavior. If no endpoint matches, the typical result is 404 Not Found.
5.8 Conventional routing
Conventional routing uses a shared pattern that maps URL segments to controller and action names.
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
| URL | Controller | Action | Route value |
|---|---|---|---|
/ | Home | Index | None |
/Products | Products | Index | None |
/Products/Details/42 | Products | Details | id = 42 |
This is useful for MVC applications with consistent controller/action conventions.
5.9 Attribute routing
Attribute routing declares routes directly on controllers and actions.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() =>
Ok(new[] { "Keyboard", "Mouse" });
[HttpGet("{id:int}")]
public IActionResult GetById(int id) =>
Ok(new { Id = id });
}
Routes include GET /api/products and GET /api/products/42. Attribute routing is common for APIs because URL structure is explicit near the endpoint.
5.10 Route groups in Minimal APIs
MapGroup groups related endpoints under a shared prefix and can apply shared conventions or metadata.
var products = app.MapGroup("/api/products")
.WithTags("Products");
products.MapGet("/", () => Results.Ok(new[] { "Keyboard", "Mouse" }));
products.MapGet("/{id:int}", (int id) => Results.Ok(new { id }));
Groups can also apply authorization requirements, endpoint filters, and other conventions.
5.11 Route values versus query strings
Route values commonly identify a resource or hierarchy. Query strings commonly describe filtering, sorting, search, or pagination.
| Purpose | Example |
|---|---|
| Identify product | /products/42 |
| Filter category | /products?category=keyboards |
| Pagination | /products?page=2&pageSize=20 |
| Search | /products?search=wireless |
This is a design guideline, not an absolute rule. Aim for consistent and predictable URLs.
5.12 URL generation
Use routing metadata to generate URLs rather than scattering hardcoded paths through the application.
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { id }))
.WithName("GetProductById");
Named routes are useful for generating links. In controllers, helpers such as Url.Action, CreatedAtAction, and CreatedAtRoute can generate URLs from routing metadata.
6. Important terminology
| Term | Meaning | Example |
|---|---|---|
| Routing | Matches a request to an endpoint | /products/42 |
| Endpoint | Handler plus metadata | Minimal API handler |
| Route template | Pattern describing a URL | /orders/{id:int} |
| Route parameter | Variable path segment | {id} |
| Route value | Captured value | id = 42 |
| Route constraint | Restricts matching values | {id:int} |
| Conventional routing | Shared controller/action pattern | {controller=Home}/{action=Index}/{id?} |
| Attribute routing | Route declared with attributes | [HttpGet("{id:int}")] |
| Endpoint routing | Modern endpoint selection/execution system | MapGet, MapControllers |
| Route group | Related Minimal API endpoints | MapGroup("/api/products") |
| Query string | Key/value data after ? | ?page=2 |
| Link generation | Creates URL from route metadata | CreatedAtRoute(...) |
| Route precedence | Rules used to choose between candidates | Literal vs parameter route |
| 404 | No matching endpoint/resource | Unknown path |
| 405 | Path is recognized but method unsupported | POST to GET-only route, where detected |
7. How it works internally
Step-by-step workflow
- Application startup: Endpoints are registered in
Program.cs, through controller discovery, or other endpoint-registration APIs. - Request arrival: The server creates an
HttpContext. - Candidate matching: Routing compares the path to templates and considers constraints and method metadata.
- Endpoint selection: A matching endpoint is selected; route values and endpoint metadata become available.
- Middleware processing: Authentication, authorization, CORS, logging, and other components run according to the configured pipeline.
- Endpoint execution: The selected controller action, Razor Page, or Minimal API handler runs.
- Response: The result is serialized or written and returned to the client.
If no endpoint matches, the pipeline may continue without a selected endpoint. A fallback endpoint or custom middleware can affect the response; a typical API ultimately returns 404.
Route precedence
More specific literal paths generally take precedence over parameter routes.
app.MapGet("/products/search", () => Results.Ok("Search"));
app.MapGet("/products/{id:int}", (int id) => Results.Ok(new { id }));
/products/search is a literal path and is more specific than a generic parameter route. Constraints narrow candidate matches. If two endpoints remain equally valid and cannot be disambiguated, ASP.NET Core can report an ambiguous match.
Do not use registration order as a substitute for clear route design.
8. Syntax explained
Minimal API syntax
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { ProductId = id }));
| Part | Meaning |
|---|---|
app | Configured WebApplication |
MapGet | Registers a GET endpoint |
"/products/{id:int}" | Template with integer constraint |
(int id) | Handler parameter bound from route value |
Results.Ok(...) | Creates a 200 OK result |
Controller syntax
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult GetById(int id) => Ok(new { id });
}
[Route("api/products")]sets the controller prefix.[HttpGet("{id:int}")]adds a GET route.{id:int}captures an integer-shaped value.GetById(int id)receives the bound value.Ok(...)returns a 200 response.
Conventional route syntax
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
nameidentifies the route for URL generation.patterndefines the URL shape.{controller=Home}defaults the controller.{action=Index}defaults the action.{id?}makes the segment optional.
9. Code examples
9.1 Simple example: route parameters
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Routing demo");
app.MapGet("/products/{id:int}", (int id) =>
{
return Results.Ok(new
{
ProductId = id,
Message = $"You requested product {id}"
});
});
app.MapGet("/articles/{slug}", (string slug) =>
Results.Ok(new { ArticleSlug = slug }));
app.Run();
Try GET /, GET /products/42, GET /products/abc, and GET /articles/routing-basics. The integer route matches /products/42, but not /products/abc.
9.2 Intermediate example: grouped endpoints
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var products = app.MapGroup("/api/products")
.WithTags("Products");
products.MapGet("/", () =>
{
var items = new[]
{
new { Id = 1, Name = "Keyboard" },
new { Id = 2, Name = "Mouse" }
};
return Results.Ok(items);
})
.WithName("GetProducts");
products.MapGet("/{id:int}", (int id) =>
{
if (id <= 0)
return Results.BadRequest(new { error = "ID must be positive." });
// Demo only: a real app would use an application service or database.
return Results.Ok(new { Id = id, Name = $"Product {id}" });
})
.WithName("GetProductById");
app.Run();
This demonstrates route groups, typed parameters, named endpoints, and a basic validation check. In production, keep business logic in application services.
9.3 Production-oriented example: controller routes and URL generation
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
// Demonstration only. Use a database-backed service in production.
private static readonly Dictionary<int, ProductDto> Products = new()
{
[1] = new ProductDto(1, "Keyboard"),
[2] = new ProductDto(2, "Mouse")
};
[HttpGet]
public ActionResult<IReadOnlyCollection<ProductDto>> GetAll() =>
Ok(Products.Values.ToArray());
[HttpGet("{id:int:min(1)}", Name = "GetProductById")]
public ActionResult<ProductDto> GetById(int id)
{
if (!Products.TryGetValue(id, out var product))
return NotFound();
return Ok(product);
}
[HttpPost]
public ActionResult<ProductDto> Create(CreateProductRequest request)
{
// Demo only: production code should persist via a service.
var id = Products.Keys.DefaultIfEmpty(0).Max() + 1;
var product = new ProductDto(id, request.Name);
Products[id] = product;
return CreatedAtRoute("GetProductById", new { id }, product);
}
}
public sealed record ProductDto(int Id, string Name);
public sealed record CreateProductRequest(string Name);
Production notes: The in-memory dictionary is only illustrative, isn't persistent, and is not a suitable concurrent data store. Use application services, persistence, validation, and integration tests. Configure authentication and authorization as required. Keep controller and DTO types in separate files in a real project.
10. Recommended folder structure
ProductApi/
├── Controllers/
│ └── ProductsController.cs
├── Contracts/
│ ├── CreateProductRequest.cs
│ └── ProductResponse.cs
├── Services/
│ ├── IProductService.cs
│ └── ProductService.cs
├── Data/
│ └── AppDbContext.cs
├── Program.cs
└── ProductApi.csproj
Routing is configured in Program.cs, endpoint registration, and controller attributes. Keep business rules out of route templates and constraints.
11. Execution flow: one request
Given GET /api/products/42 and a controller with [Route("api/products")] plus [HttpGet("{id:int}")]:
- The server receives the request and creates the context.
- Routing compares the URL to registered endpoint patterns.
- The controller prefix and action template combine into
api/products/{id:int}. - The value
42satisfies the integer constraint. - Routing selects the endpoint and records
id = 42. - Authentication and authorization run as configured.
- ASP.NET Core invokes the action with
id = 42. Ok(...)creates a 200 result.- ASP.NET Core serializes the response and sends it.
For /api/products/abc, this constrained route doesn't match. Another endpoint might handle the path; otherwise, the usual result is 404.
12. Real project usage
| Industry | Example routes | Why routing matters |
|---|---|---|
| E-commerce | /api/products/42, /api/orders/1001 | Separates catalog, checkout, and order operations |
| Banking | /api/accounts/{accountId}/transactions | Models account resources; authorization protects sensitive data |
| Healthcare | /api/patients/{patientId}/appointments | Organizes patient and appointment operations with strict access controls |
| Logistics | /api/shipments/{trackingNumber} | Supports shipment lookup and tracking |
| Social media | /api/users/{userId}/posts, /api/posts/{postId}/comments | Models users, posts, and comments |
| Enterprise software | /api/tenants/{tenantId}/reports | Organizes tenant resources; tenant identity must be validated |
These are illustrative URL designs. A route containing an identifier does not automatically protect the resource; the app must check the caller's permission.
13. Performance considerations
Memory
- Route templates and endpoint metadata are generally built at startup and reused.
- Avoid unnecessary large objects in handlers.
- Do not store request-specific values in static fields.
- Avoid redundant endpoints and overly complicated route designs.
CPU
- Route matching evaluates candidates, constraints, and metadata.
- Clear routes reduce ambiguity and improve maintainability.
- Avoid database calls or expensive computation during routing decisions.
- Use constraints for simple shape-based matching, not business rules.
Scalability
- Routing is rarely the main bottleneck in a well-designed application.
- Database queries, external services, serialization, and expensive middleware often dominate latency.
- Use asynchronous I/O in handlers.
- Register endpoints deterministically; don't rebuild routing structures per request.
Optimization checklist
- Use consistent route patterns.
- Avoid overlapping templates.
- Use URL-generation helpers instead of hardcoded paths.
- Measure before optimizing.
- Observe endpoint latency and status-code patterns.
14. Security considerations
Routing organizes requests; it is not a security boundary.
Common risks
- IDOR: A caller changes
/accounts/100to/accounts/101and tries to access another user's account. - Tenant boundary mistakes: The app trusts
{tenantId}without checking membership. - Overly broad fallback routes: A catch-all route absorbs unexpected paths.
- Information leakage: Different error behavior reveals whether a sensitive resource exists.
- Unsafe redirects: Unvalidated user-provided URLs can cause open redirects.
Best practices
- Require authentication and authorization where appropriate.
- Authorize access to the specific resource, not just the endpoint.
- Validate tenant and ownership boundaries in application logic.
- Use constraints for simple formats, not access control.
- Avoid catch-all routes unless their behavior is explicit.
- Use framework URL generation.
- Validate redirect targets; use local-URL checks for internal redirects.
- Return safe errors without exposing internal details.
- Test wrong-user, wrong-tenant, malformed-ID, unsupported-method, and unknown-path cases.
Warning:
/api/accounts/{accountId}only extracts an ID. It does not prove that the current user is allowed to access the account.
15. Ten common beginner mistakes
- Confusing routing with middleware. Routing selects an endpoint; middleware performs cross-cutting request/response work. Keep the responsibilities clear.
- Ignoring HTTP methods. A URL path doesn't describe every operation. Register GET, POST, PUT, and DELETE intentionally.
- Using constraints as business validation. A failed constraint can make the route not match. Validate domain rules in application logic.
- Creating ambiguous templates. Overlapping patterns may leave equally valid candidates. Use specific routes and test collisions.
- Using route parameters for every filter. Use query strings for pagination, sorting, and filtering when appropriate.
- Hardcoding URLs everywhere. Use named routes and URL-generation helpers to avoid broken links after route changes.
- Assuming a matching route grants access. Always check authentication, authorization, resource ownership, and tenant boundaries.
- Misunderstanding optional segments. Test routes both with and without optional values, and ensure handler binding supports omission.
- Using catch-all routes too broadly. They can swallow requests intended for other endpoints. Keep fallback behavior explicit.
- Confusing 404 and 405. A 404 generally means no matching endpoint/resource; a 405 indicates a recognized path with an unsupported method when detected by the configured endpoint system.
16. Production best practices
- Design resource-oriented URLs.
- Use HTTP methods intentionally.
- Prefer attribute routing for explicit controller APIs.
- Use conventional routing when it genuinely simplifies an MVC application.
- Use
MapGroupfor related Minimal APIs. - Apply constraints to simple value shapes.
- Keep business validation out of route constraints.
- Avoid ambiguous templates.
- Use named routes when generating links.
- Give route parameters meaningful names.
- Use query strings for filtering and pagination when appropriate.
- Return status codes that reflect the actual outcome.
- Secure each sensitive resource separately from route matching.
- Test malformed and unauthorized requests.
- Keep endpoint registration readable and deterministic.
- Avoid catch-all routes unless needed.
- Treat public URLs as part of the API contract.
- Document APIs with OpenAPI.
- Use URL-generation helpers for redirects and resource links.
- Measure before optimizing routing.
- Avoid leaking internal details in error responses.
- Keep handlers thin and delegate business logic to services.
- Validate identifiers and request payloads.
- Test route precedence, literal routes, parameters, and constraints.
- Review fallback endpoints for unintended exposure.
17. Interview questions and answers
Beginner questions
1. What is routing in ASP.NET Core?
Routing matches incoming HTTP requests to endpoints using paths, methods, templates, constraints, and metadata. It directs requests to controllers, Razor Pages, or Minimal API handlers.
2. What is an endpoint?
An executable request handler plus metadata used for selection and processing. A Minimal API handler or controller action can be an endpoint.
3. What is a route template?
A pattern describing a URL, such as /products/{id:int}. The placeholder captures a value from the path.
4. What is a route parameter?
A variable path segment, such as {id} in /products/{id}. The value from /products/42 can be bound to id.
5. What is endpoint routing?
ASP.NET Core's system for selecting registered endpoints and executing the selected handler through the request pipeline.
6. What is conventional routing?
A shared route pattern commonly maps URL segments to controller/action conventions, such as {controller=Home}/{action=Index}/{id?}.
7. What is attribute routing?
Routes are declared directly on controllers and actions with attributes such as [Route], [HttpGet], and [HttpPost].
8. What is a route constraint?
A rule that limits which values match a route, such as {id:int}.
9. Route values versus query strings?
Route values commonly identify a resource, like /products/42. Query strings commonly refine a result, like /products?page=2.
10. What is the difference between 404 and 405?
404 usually means no matching endpoint/resource was found. 405 means the path is recognized but the method is unsupported, when the configured endpoint system can detect it.
Intermediate questions
11. Conventional routing vs attribute routing?
Conventional routing defines shared patterns and uses conventions. Attribute routing declares the public route near the controller/action. Attribute routing is common in APIs because paths are explicit.
12. How does ASP.NET Core choose among matching routes?
It evaluates templates, constraints, and endpoint metadata. More specific patterns generally take precedence. Equally valid candidates can cause an ambiguous match.
13. What is MapGroup?
It groups Minimal API endpoints under a shared prefix and lets them share conventions or metadata, such as authorization, tags, and filters.
14. app.Map vs app.MapGet?
app.Map creates a path-based middleware branch. app.MapGet registers a GET endpoint through endpoint routing.
15. Do constraints replace validation?
No. Constraints help select matching endpoints. Business rules belong in model validation, application services, or domain logic.
16. How do you make a parameter optional?
Use ?, as in /archive/{year?}, and ensure handler binding and behavior support the omitted value.
17. How do you define default route values?
Use defaults in a conventional route pattern, such as {controller=Home}, or provide defaults through route registration.
18. Why use named routes?
They let code generate URLs from routing metadata rather than hardcoded strings, useful for redirects and created-resource responses.
19. Can two endpoints share a route template?
Yes, if metadata such as HTTP method distinguishes them. If candidates remain equally valid, the request can be ambiguous.
20. How does routing relate to middleware?
Routing is integrated into the middleware pipeline. Route matching makes endpoint metadata available to later middleware; endpoint execution invokes the selected handler.
Advanced questions
21. What is endpoint metadata?
Metadata describes endpoint behavior or requirements, such as HTTP methods, authorization policies, CORS settings, route names, or OpenAPI information.
22. Why can a failed constraint lead to 404 instead of 400?
A constraint affects matching. If {id:int} receives non-integer text, that endpoint isn't a match. If nothing else matches, the response is usually 404. Use validation to return 400 when a matched operation receives invalid input.
23. What causes ambiguous route matching?
Multiple endpoints remain equally valid and the framework cannot choose. Fix overlapping templates, method metadata, or constraints rather than relying on registration order.
24. How would you design routes for a multi-tenant API?
Use consistent resource-oriented paths, but validate tenant context, authenticate the caller, enforce tenant membership and ownership, and test cross-tenant access attempts.
25. How can route design affect backward compatibility?
Public routes are part of the API contract. Changing them can break clients, bookmarks, integrations, and generated links. Plan versioning and deprecation deliberately.
26. How does precedence work for literal and parameter segments?
A literal such as /products/search is generally more specific than /products/{id}. Constraints narrow candidates further; route behavior should still be explicit and tested.
27. What is a catch-all route?
A template such as {**path} can capture multiple remaining path segments. It is useful for specific scenarios but can absorb requests unexpectedly if too broad.
28. How do you troubleshoot 404 responses?
Check the exact path and method, endpoint registration, controller discovery, constraints, optional/default values, path base or proxy configuration, and middleware that might short-circuit the request.
29. How do you generate a URL after POST?
Use CreatedAtAction, CreatedAtRoute, or Minimal API URL-generation features with a named endpoint. This avoids hardcoded URLs and can return a Location header.
30. What security issue can occur with ID route parameters?
IDOR: a handler loads a resource by ID without verifying the caller's permission. Enforce resource-level authorization and tenant boundaries.
18. Hands-on exercise
Build a Product API with these requirements:
GET /api/productslists products.GET /api/products/{id:int}returns one product.POST /api/productscreates a product and returns201 CreatedwithLocation.DELETE /api/products/{id:int}returns204 No Contentwhen successful.- Invalid IDs return a suitable error.
- Unknown IDs return 404.
- Use a named route and URL generation rather than hardcoding the
LocationURL. - Write integration tests for valid IDs, invalid IDs, missing resources, and unsupported methods.
| Test | Expected behavior |
|---|---|
GET /api/products | 200 OK |
GET /api/products/1 | 200 if it exists |
GET /api/products/abc | Integer route doesn't match; usually 404 unless another route handles it |
GET /api/products/9999 | 404 if no such product exists |
| Successful POST | 201 Created and Location |
| Successful DELETE | 204 No Content |
| Unsupported method | Appropriate 405 behavior where supported |
Stretch goal: Add authorization to DELETE and test that a caller without permission cannot delete a product.
19. Mini project: route-driven catalog API
Goal: Build a catalog API that demonstrates route templates, constraints, query parameters, route groups, and URL generation.
| Method | Route | Purpose |
|---|---|---|
| GET | /api/catalog/products | List products |
| GET | /api/catalog/products/{id:int} | Get one product |
| GET | /api/catalog/products/search?term=... | Search products |
| POST | /api/catalog/products | Create product |
| DELETE | /api/catalog/products/{id:int} | Delete product |
Implementation plan
- Create a .NET 9+ Web API project.
- Create request/response DTOs.
- Create
IProductServiceandProductService. - Register the service through dependency injection.
- Group endpoints with
MapGroup("/api/catalog/products"). - Add an integer constraint to the ID route.
- Use query parameters for search and pagination.
- Name the get-by-ID endpoint and generate the created-resource URL.
- Add validation and consistent errors.
- Add integration tests for matching and failure cases.
var products = app.MapGroup("/api/catalog/products")
.WithTags("Catalog");
products.MapGet("/", async (
IProductService service,
CancellationToken cancellationToken) =>
{
var result = await service.GetAllAsync(cancellationToken);
return Results.Ok(result);
});
products.MapGet("/{id:int}", async (
int id,
IProductService service,
CancellationToken cancellationToken) =>
{
var product = await service.GetByIdAsync(id, cancellationToken);
return product is null
? Results.NotFound()
: Results.Ok(product);
});
The service interface and DTOs are left as exercises so you can practice designing the application structure.
20. Quiz: multiple-choice questions
Q1. What is routing's main purpose?
A. Save data to a database
B. Match requests to endpoints
C. Authenticate every user
D. Serialize responses manually
Correct answer: B. Routing selects the endpoint. Authentication, persistence, and serialization are separate responsibilities.
Q2. Which template requires an integer-shaped route value?
A. /products/{id}
B. /products/{id:int}
C. /products?id=int
D. /products/{int}
Correct answer: B. The int constraint restricts route matching to integer-shaped values.
Q3. Which style uses [HttpGet] attributes?
A. Attribute routing
B. Query routing
C. File routing
D. Database routing
Correct answer: A. Attribute routing declares templates on controllers and actions.
Q4. What is MapGroup for?
A. Creating database tables
B. Grouping Minimal API endpoints with shared prefixes/conventions
C. Encrypting route values
D. Replacing authorization
Correct answer: B. Groups reduce repetition and allow shared metadata.
Q5. Which is a common query-string use?
A. Store a password
B. Replace authentication
C. Specify pagination
D. Identify every resource uniquely
Correct answer: C. Query strings commonly handle filtering, sorting, search, and pagination.
Q6. Does {id:int} ensure the caller can access the record?
A. Always
B. If the ID is positive
C. No; authorization is separate
D. Only for controllers
Correct answer: C. A constraint affects matching, not user permissions.
Q7. What does a named route help with?
A. URL generation from routing metadata
B. Replacing DTOs
C. Running SQL queries
D. Encrypting responses
Correct answer: A. Named routes reduce hardcoded path strings.
Q8. Which status generally means no endpoint/resource was found?
A. 200
B. 201
C. 404
D. 500
Correct answer: C. 404 is the usual not-found response, subject to app configuration.
Q9. What can cause an ambiguous match?
A. Two equally valid endpoints match
B. A controller uses a DTO
C. Dependency injection is enabled
D. A response has a body
Correct answer: A. Overlapping templates without enough distinguishing metadata can leave multiple candidates.
Q10. Which statement is correct?
A. Routing authorizes every resource
B. Constraints replace business validation
C. Routing selects endpoints; authorization protects access
D. Every endpoint needs a controller
Correct answer: C. Routing and authorization solve different problems.
21. Summary
One-minute revision
Routing matches requests to endpoints. Route templates describe URL shapes; parameters capture values; constraints restrict matches. Conventional routing uses shared controller/action patterns, attribute routing declares routes on controllers/actions, and Minimal APIs use methods such as MapGet and MapPost. MapGroup organizes related endpoints. Routing selects the endpoint, but authorization still determines whether the caller may access the resource.
Five-minute revision
- Endpoint: Handler plus metadata.
- Endpoint routing: Matches requests to registered endpoints.
- Route template: Pattern such as
/products/{id:int}. - Route parameter: Variable path segment.
- Constraint: Matching rule such as
:intor:guid. - Conventional routing: Shared controller/action patterns.
- Attribute routing: Routes declared with attributes.
- Minimal API routing:
MapGet,MapPost, and related methods. - Route groups: Shared prefixes/conventions through
MapGroup. - URL generation: Creates links from routing metadata.
- Security: Resource access must be authorized separately.
- Testing: Cover valid paths, malformed values, unknown resources, wrong methods, and authorization failures.
Bullet-point summary
- Routing directs requests to endpoints.
- Paths, methods, constraints, and metadata all matter.
- Constraints don't replace domain validation.
- Use route values for resource identity and query strings for filtering where appropriate.
- Named routes reduce hardcoded URLs.
- Clear route templates prevent ambiguity.
- Authorization and tenant checks are separate from routing.
Memory tricks
- Route = Where? Which endpoint?
- HTTP method = What action? Read, create, update, delete?
- Constraint = Shape? Integer, GUID, or other format?
- Authorization = Allowed? May this caller access the resource?
- Route values identify; query strings refine.
Flashcards
| Front | Back |
|---|---|
| What does routing do? | Matches requests to endpoints. |
What does {id:int} mean? | Integer-constrained route parameter. |
| What is attribute routing? | Routes declared with controller/action attributes. |
What does MapGroup do? | Groups Minimal APIs under shared prefixes and conventions. |
| Do constraints authorize access? | No; authorization is separate. |
| When is a query string useful? | Filtering, sorting, search, and pagination. |
22. Cheat sheet
| Task | Example |
|---|---|
| GET endpoint | app.MapGet("/products", handler); |
| POST endpoint | app.MapPost("/products", handler); |
| Integer ID | "/products/{id:int}" |
| GUID ID | "/orders/{id:guid}" |
| Optional segment | "/archive/{year?}" |
| Controller prefix | [Route("api/products")] |
| Controller GET action | [HttpGet("{id:int}")] |
| Conventional MVC route | "{controller=Home}/{action=Index}/{id?}" |
| Group endpoints | app.MapGroup("/api/products") |
| Name endpoint | .WithName("GetProductById") |
| Created response | CreatedAtRoute("GetProductById", new { id }, product) |
| Not found | Results.NotFound() / NotFound() |
| OK response | Results.Ok(value) / Ok(value) |
| No content | Results.NoContent() / NoContent() |
| Resource identity | /products/42 |
| Pagination | /products?page=2&pageSize=20 |
| No matching route | Usually 404 |
| Unsupported method | Often 405 when detected |
23. Comparison table
Conventional routing vs attribute routing
| Aspect | Conventional | Attribute |
|---|---|---|
| Definition | Shared patterns | Attributes on controllers/actions |
| URL visibility | Centralized | Near endpoint code |
| Common use | Convention-driven MVC | Explicit APIs |
| Example | {controller=Home}/{action=Index}/{id?} | [HttpGet("api/products/{id:int}")] |
Route parameters vs query strings
| Aspect | Route parameter | Query string |
|---|---|---|
| Typical purpose | Resource identity/hierarchy | Filtering, sorting, pagination |
| Example | /products/42 | /products?page=2 |
| Design question | Which resource? | Which subset/view? |
Routing vs middleware
| Aspect | Routing | Middleware |
|---|---|---|
| Responsibility | Select endpoint | Cross-cutting request/response work |
| Example | Match /products/42 | Log duration or handle exceptions |
| Business logic | Not normally | Not normally |
| Relationship | Integrated into pipeline | Can inspect endpoint metadata after routing |
Routing vs authorization
| Aspect | Routing | Authorization |
|---|---|---|
| Main question | Which endpoint matches? | Is caller allowed? |
| Inputs | Path, method, constraints, metadata | Identity, claims, policies, resource rules |
| Example | /accounts/123 matches | User may or may not access account 123 |
24. Key takeaways
- Routing maps HTTP requests to endpoints.
- Endpoint routing is the modern ASP.NET Core model.
- Templates can include parameters, optional segments, defaults, and constraints.
- Conventional and attribute routing are both useful.
- Route groups improve consistency in Minimal APIs.
- Named endpoints and URL-generation helpers reduce hardcoded paths.
- Constraints don't replace business validation.
- Routing doesn't replace authentication, authorization, or ownership checks.
- Fix route ambiguity through clear design and tests.
- Public URL patterns are part of the API contract.
25. Revision checklist
- I can explain routing without confusing it with authorization.
- I understand endpoint routing at a high level.
- I can read and write route templates.
- I understand required, optional, and default route values.
- I can use common route constraints.
- I understand conventional and attribute routing.
- I can register Minimal API endpoints and route groups.
- I can distinguish route values from query strings.
- I understand precedence and ambiguous matches.
- I can generate URLs using named routes.
- I can explain 404 versus 405.
- I can test route matching and failures.
- I know that resource authorization must be implemented separately.
26. Further reading
Continue with these related Logic Lense Roadmaps articles:
- Middleware Pipeline — Understand request processing before and after endpoint execution.
- Controller — Learn how controllers and action methods handle routed requests.
- Minimal APIs in ASP.NET Core — Build HTTP endpoints without controller classes.
- Razor Pages in ASP.NET Core — Learn page-focused routing and handler methods.
- Dependency Injection in ASP.NET Core — Understand how handlers and controllers receive services.
- Authentication and Authorization in ASP.NET Core — Identify callers and protect endpoints.
- REST API Design — Design consistent resource paths and HTTP operations.
Last updated 10/25/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
