🧠Key Takeaways: Understand how ASP.NET Core routing works under the hood. Build custom constraints, transformers, and matchers for complete control.
Routing is the heart of ASP.NET Core. Mastering it gives you complete control over request handling.
🎯 Routing Fundamentals
// ✅ Basic routing
app.MapGet("/api/products/{id}", async (int id, IProductService service) =>
{
return await service.GetProductAsync(id);
});
// ✅ Custom constraint
app.MapGet("/api/products/{id:min(1):max(100)}", async (int id) =>
{
// Only allows IDs between 1 and 100
return Results.Ok(id);
});
// ✅ Custom route transformer
app.MapGet("/api/products/{slug:slugify}", async (string slug) =>
{
// Converts "gaming-laptop" to "Gaming Laptop"
return Results.Ok(slug);
});
💡 Custom Route Constraint
// ✅ Create custom constraint
public class SlugifyRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey,
RouteValueDictionary values, RouteDirection routeDirection)
{
if (values.TryGetValue(routeKey, out var value))
{
var slug = value?.ToString();
if (string.IsNullOrEmpty(slug)) return false;
// ✅ Valid slug: lowercase, alphanumeric, hyphens
return slug.All(c => char.IsLetterOrDigit(c) || c == '-');
}
return false;
}
}
// Register constraint
builder.Services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("slug", typeof(SlugifyRouteConstraint));
});
// Usage
app.MapGet("/api/posts/{slug:slug}", async (string slug) =>
{
// Works only with valid slugs
return await _postService.GetBySlugAsync(slug);
});
💡 Custom Route Transformer
// ✅ Route transformer for parameter transformation
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
if (value == null) return null;
var str = value.ToString();
// Transform "Gaming Laptop" to "gaming-laptop"
return str.ToLower().Replace(" ", "-");
}
}
// Apply transformer
builder.Services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("slugify", typeof(SlugifyParameterTransformer));
});
// Usage - Generates clean URLs
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet("{name:slugify}")]
public IActionResult GetProduct(string name)
{
// URL: /api/products/gaming-laptop
return Ok(name);
}
}
