How do you generate a URL for a named route or endpoint programmatically, rather than hardcoding URL strings throughout the application (like in a Location header for a 201 Created response)?
Short answer
Named endpoints (via .WithName("GetProduct") in minimal APIs or route names in controller attributes) can be referenced by LinkGenerator.GetPathByName() or Results.CreatedAtRoute()/CreatedAtAction() to generate the correct URL dynamically, ensuring links stay correct even if the…
Advertisement
AModel answer
Named endpoints (via .WithName("GetProduct") in minimal APIs or route names in controller attributes) can be referenced by LinkGenerator.GetPathByName() or Results.CreatedAtRoute()/CreatedAtAction() to generate the correct URL dynamically, ensuring links stay correct even if the underlying route template changes later, rather than hardcoding a URL string that could silently become stale.
app.MapGet("/products/{id}", GetById).WithName("GetProduct");
app.MapPost("/products", (ProductDto dto) => {
var product = _service.Create(dto);
return Results.CreatedAtRoute("GetProduct", new { id = product.Id }, product);
// generates the correct Location header URL by referencing the named route
});Real-world example
A POST endpoint creating a new product returns a 201 Created response with a correctly-generated Location header pointing to the new resource, using CreatedAtRoute referencing the named GetProduct route rather than manually string-concatenating a URL that could drift out of sync if the route template ever changes.
Likely follow-ups
- What is REST's requirement around returning a Location header for 201 responses, and why does this matter?
- How does LinkGenerator work outside the context of an active HTTP request, like in a background service sending an email with a link?
Related topics