ASP.NET Core Routing

Routing is a core concept in ASP.NET Core applications. It's the process of matching an incoming HTTP request to a specific endpoint (such as an action method in an MVC controller or a Razor Page handler). This documentation covers the fundamentals and advanced features of ASP.NET Core routing.

Introduction to Routing

ASP.NET Core's routing system is designed to be flexible and powerful, allowing you to define complex URL patterns and map them to your application's logic. It uses a convention-based and code-based approach.

Core Concepts

Route Constraints

Route constraints allow you to specify rules for the values of route parameters. For example, you can require a parameter to be a number or a specific string format.


app.MapGet("/products/{id:int}", (int id) => $"Product ID: {id}");
app.MapGet("/users/{username:alpha}", (string username) => $"Username: {username}");
                

Optional Parameters

You can define parameters as optional by using the ? suffix.


app.MapGet("/archive/{year:int}/{month:int?}", (int year, int? month) => {
    if (month.HasValue) {
        return $"Archive for {year}/{month.Value}";
    } else {
        return $"Archive for {year}";
    }
});
                

Attribute Routing

Attribute routing provides a way to define routes directly on controller actions or Razor Page handlers using attributes like [Route] and [HttpGet]. This is often preferred for its clarity and ease of use.


[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetProduct(int id)
    {
        return Ok($"Product {id}");
    }

    [HttpPost]
    public IActionResult CreateProduct()
    {
        return CreatedAtAction(nameof(GetProduct), new { id = 1 }, null);
    }
}
                

For Razor Pages, you can use the [Route] attribute on the page itself.


@page "/products/{id:int}"
@model ProductsModel
...
                

Endpoint Routing

ASP.NET Core utilizes a sophisticated endpoint routing system that allows for efficient matching of requests. Key components include route templates, route values, and route matching.

Endpoint routing has replaced the older MVC-style routing system and offers improved performance and flexibility.

Configuring Routes

Routes can be configured in the Program.cs file using extension methods like MapGet, MapPost, MapControllerRoute, and MapRazorPages.


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapRazorPages();

app.Run();
                

Routing in Minimal APIs

Minimal APIs provide a concise way to define endpoints without the need for controllers or explicit routing configuration in many cases.


var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapGet("/hello/{name}", (string name) => $"Hello, {name}!");

app.Run();
                

Advanced Routing Scenarios

Route Groups

You can group related endpoints together for better organization and to apply common prefixes or metadata.


var adminApi = app.MapGroup("/admin");
adminApi.MapGet("/users", () => "Admin users");
adminApi.MapPost("/products", () => "Create admin product");
                

Parameter Transformers

Customize how route parameter values are converted to their target types.

Further Reading