Routing in ASP.NET
Overview
Routing maps incoming HTTP requests to route handlers. In ASP.NET Core, routing is a core part of the request pipeline and works together with the endpoint routing system to dispatch requests to the appropriate controller actions, Razor pages, or custom handlers.
Basic Routing
Define routes in Startup.cs
or Program.cs
using MapControllerRoute
for conventional routing.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
The pattern consists of placeholders that are replaced with request URL segments.
Attribute Routing
Apply route templates directly to controller actions using attributes.
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult Get(int id)
{
// ...
}
}
Attribute routing provides fine‑grained control and eliminates the need for a global route definition.
Route Constraints
Constraints restrict which URLs match a route. Common constraints include int
, guid
, regex
, and custom constraints.
[HttpGet("orders/{orderId:guid}")]
public IActionResult GetOrder(Guid orderId) { ... }
Custom Route Handlers
Implement IRouter
or use Endpoint
to create custom routing logic.
public class LegacyRouter : IRouter
{
public VirtualPathData GetVirtualPath(VirtualPathContext context) => null;
public Task RouteAsync(RouteContext context)
{
// custom handling
return Task.CompletedTask;
}
}
Routing Middleware
In ASP.NET Core, routing is added to the middleware pipeline with UseRouting
and UseEndpoints
.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Full Example
A minimal API with routing.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Welcome to ASP.NET Core!");
app.MapGet("/weather/{city}", (string city) =>
{
return $"Weather forecast for {city}";
});
app.Run();