Endpoint Routing in ASP.NET Core
Endpoint Routing provides a unified routing system that decouples the definition of routes from the middleware pipeline. It enables flexible request matching and improves performance by allowing the framework to select endpoints before executing middleware.
Key Concepts
- Endpoint: A representation of a route with associated metadata and a request delegate.
- Matcher: The component that selects an endpoint based on the incoming request.
- Route Pattern: A string that defines URLs and constraints.
Setting Up Endpoint Routing
In Program.cs
or Startup.cs
, add the routing middleware before other middleware that needs routing information.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting(); // Adds routing middleware
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.Run();
Attribute Routing
Controllers and Razor Pages can define routes directly on actions or pages.
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult Get(int id) => Ok(new { Id = id });
}
Advanced Scenarios
Custom Constraints
endpoints.MapGet("/orders/{orderId:guid}", async context =>
{
var orderId = context.Request.RouteValues["orderId"];
await context.Response.WriteAsync($"Order ID: {orderId}");
});
Endpoints with Metadata
Metadata can be added to endpoints for policies like authorization.
endpoints.MapGet("/admin", async context =>
{
await context.Response.WriteAsync("Admin Area");
}).RequireAuthorization("AdminPolicy");
Performance Tips
- Place
app.UseRouting()
as early as possible. - Combine static file middleware before routing to reduce unnecessary processing.
- Use
MapFallback
for catch‑all routes.
Further Reading
Explore related topics: