ASP.NET Core Fundamentals: Routing
Quick Answer
Routing in ASP.NET Core maps incoming HTTP requests to controller actions or endpoints. It uses route templates and supports attribute routing, enabling flexible URL patterns and parameters to build RESTful APIs and web apps.
Learning Objectives
- Explain the purpose of Routing in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Routing.
- Apply Routing in a simple real-world scenario or practice task.
Introduction to Routing in ASP.NET Core
Routing is a core feature of ASP.NET Core that directs incoming HTTP requests to the appropriate controller actions or endpoints.
It enables developers to define URL patterns that map to specific code, making web applications and APIs intuitive and RESTful.
Understanding routing is essential for building scalable and maintainable ASP.NET Core applications.
Routing is the mechanism that maps URLs to code.
What is Routing?
Routing is the process of matching an incoming HTTP request to a route handler, such as a controller action or Razor page.
In ASP.NET Core, routing is flexible and supports both convention-based and attribute-based approaches.
- Maps URLs to code endpoints
- Supports parameters in URLs
- Enables RESTful API design
- Works with middleware pipeline
Route Templates and Parameters
Route templates define URL patterns with placeholders for parameters.
Parameters can be required or optional and can have default values.
- Use curly braces {} to define parameters, e.g., "products/{id}"
- Parameters can be constrained by type, e.g., "{id:int}"
- Optional parameters use a question mark, e.g., "{id?}"
- Default values can be set in route templates
| Constraint | Description | Example |
|---|---|---|
| int | Matches integer values | {id:int} |
| bool | Matches boolean values | {isActive:bool} |
| datetime | Matches date/time values | {date:datetime} |
| alpha | Matches alphabetic characters only | {name:alpha} |
| length | Matches string length |
Convention-Based Routing
Convention-based routing defines routes centrally, often in the Startup.cs file.
It uses route templates to map URL patterns to controllers and actions.
- Defined in the Configure method using UseEndpoints or UseMvc
- Supports default routes like "{controller=Home}/{action=Index}/{id?}"
- Easy to maintain for simple applications
Attribute Routing
Attribute routing allows defining routes directly on controllers and actions using attributes.
It provides fine-grained control over URL patterns and is ideal for REST APIs.
- Use [Route], [HttpGet], [HttpPost], etc. attributes
- Supports route parameters and constraints inline
- Enables multiple routes per action if needed
Route Constraints and Custom Constraints
Route constraints restrict the values that route parameters can accept.
Custom constraints can be created by implementing IRouteConstraint.
- Built-in constraints include int, bool, datetime, alpha, length, and regex
- Custom constraints validate parameters with custom logic
- Constraints improve route matching accuracy and security
Examples of Routing in ASP.NET Core
Here are practical examples demonstrating routing concepts.
Convention-Based Routing Example
This example shows a default route defined in Startup.cs.
Attribute Routing Example
This example shows how to use attribute routing on a controller.
Practical Example
Defines a default route where the URL pattern maps to controller, action, and an optional id parameter.
Defines a route prefix 'api/products' and an action route with an integer id parameter.
Examples
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});Defines a default route where the URL pattern maps to controller, action, and an optional id parameter.
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult GetProduct(int id)
{
// Retrieve product by id
return Ok();
}
}Defines a route prefix 'api/products' and an action route with an integer id parameter.
Best Practices
- Use attribute routing for APIs to have clear and maintainable routes.
- Define route constraints to validate parameters and avoid ambiguous matches.
- Keep route templates simple and consistent across the application.
- Use optional parameters sparingly to avoid complex route matching.
- Test routes thoroughly to ensure correct endpoint mapping.
Common Mistakes
- Defining conflicting routes that cause ambiguous matches.
- Not using route constraints, leading to unexpected parameter binding.
- Overusing optional parameters, making routes hard to predict.
- Mixing convention-based and attribute routing without clear strategy.
- Ignoring route order when using multiple route definitions.
Hands-on Exercise
Create a Custom Route Constraint
Implement a custom route constraint that only matches GUID parameters.
Expected output: A route that only matches GUID formatted parameters.
Hint: Implement the IRouteConstraint interface and register it in Startup.cs.
Define Attribute Routes for a Blog Controller
Create attribute routes for actions to handle listing posts, viewing a post by slug, and creating a new post.
Expected output: Correctly routed endpoints for blog operations.
Hint: Use [Route] and HTTP method attributes with parameters.
Interview Questions
What is routing in ASP.NET Core?
InterviewRouting is the process of mapping incoming HTTP requests to controller actions or endpoints based on URL patterns.
What is the difference between convention-based and attribute routing?
InterviewConvention-based routing defines routes centrally using route templates, while attribute routing defines routes directly on controllers and actions using attributes.
How do route constraints improve routing?
InterviewRoute constraints restrict parameter values to specific types or patterns, improving route matching accuracy and preventing invalid requests.
MCQ Quiz
1. What is the best first step when learning Routing?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Routing?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. Routing in ASP.NET Core maps incoming HTTP requests to controller actions or endpoints.
B. Routing never needs examples
C. Routing is unrelated to practical work
D. Routing should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Routing in ASP.NET Core maps incoming HTTP requests to controller actions or endpoints.
- It uses route templates and supports attribute routing, enabling flexible URL patterns and parameters to build RESTful APIs and web apps.
- Routing is a core feature of ASP.NET Core that directs incoming HTTP requests to the appropriate controller actions or endpoints.
- It enables developers to define URL patterns that map to specific code, making web applications and APIs intuitive and RESTful.
- Understanding routing is essential for building scalable and maintainable ASP.NET Core applications.
Summary
Routing is a fundamental concept in ASP.NET Core that connects URLs to application logic.
Understanding route templates, parameters, constraints, and routing styles is essential for building effective web applications and APIs.
Using best practices and avoiding common mistakes ensures your routes are clear, maintainable, and performant.
Frequently Asked Questions
Can I use both convention-based and attribute routing together?
Yes, ASP.NET Core supports using both routing styles together, but it is recommended to have a clear strategy to avoid conflicts.
What happens if two routes match the same URL?
If multiple routes match a URL, ASP.NET Core selects the best match based on route order and specificity; ambiguous matches can cause runtime errors.
How do I make a route parameter optional?
Add a question mark after the parameter name in the route template, e.g., {id?}, to make it optional.
What is Routing?
Routing in ASP.NET Core maps incoming HTTP requests to controller actions or endpoints.
Why is Routing important?
It uses route templates and supports attribute routing, enabling flexible URL patterns and parameters to build RESTful APIs and web apps.
How should I practice Routing?
Routing is a core feature of ASP.NET Core that directs incoming HTTP requests to the appropriate controller actions or endpoints.

