WithName assigns a name to an ASP.NET Core endpoint as metadata. Other application code can use that name to generate links, while OpenAPI tooling can use it as an operation identifier. Names are case-sensitive and must be globally unique. section 6.4.1 section 11.4.3
Name an endpoint for link generation
app.MapGet("/product/{name}", (string name) => $"The product is {name}") .WithName("product"); app.MapGet("/links", (LinkGenerator links) => { string link = links.GetPathByName("product", new { name = "big-widget" }); return $"View the product at {link}"; }); LinkGenerator is available through dependency injection. Use GetPathByName to create a path, or GetUriByName with a scheme and host to create a complete URL. section 6.4.1
Adding WithName to API endpoints also improves generated clients: the endpoint name becomes the OpenAPI OperationID, allowing NSwag to produce clearer client method names. section 11.4.3
Listing 6.2 Generating a URL LinkGenerator and a named endpoint
app.MapGet("/product/{name}", (string name) => $"The product is {name}") #1
.WithName("product"); #2
app.MapGet("/links", (LinkGenerator links) => #3
{
string link = links.GetPathByName("product", #4
new { name = "big-widget"}); #4
return $"View the product at {link}"; #5
});
Shows the complete minimal API pattern: assign a stable endpoint name, inject LinkGenerator, and generate a path with route values. section 6.4.1
