ASP.NET Core Documentation

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

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

Further Reading

Explore related topics: