'Error when using CreatedAtRoute in ASP.NET Core minimal API
I'm trying to use CreatedAtRoute in minimal API.
app.MapGet("/clients/{id:int}", [EndpointName("GetClientById")] async (int id, ClientsContext db) =>
await db.Clients.SingleOrDefaultAsync(client => client.Id == id));
app.MapPost("/clients", async (ClientsContext db, Client client) =>
{
var newClient = db.Add(client);
await db.SaveChangesAsync();
var entity = newClient.Entity;
var url = $"{host}/clients/{newClient.Entity.Id}";
return Results.CreatedAtRoute(
routeName: "GetClientById",
routeValues: new { id = entity.Id },
value: entity);
});
I use EndpointName attribute to name the endpoint I refer to in POST request.
However, I get the exception:
System.InvalidOperationException: No route matches the supplied values.
This is strange since there's only one parameter in url pattern - id.
A little note
You can use WithName instead of [EndpointName] attribute:
app
.MapGet("/clients-m/{id:int}", async (int id, ClientsContext db) =>
await db.ClientsM.SingleOrDefaultAsync(client => client.Id == id))
.WithName("GetClientByIdAsync");
Solution 1:[1]
For minimal APIs, try using .WithName instead for setting the EndpointNameAttribute i.e.
app.MapGet("/clients/{id:int}", async (int id, ClientsContext db) =>
await db.Clients.SingleOrDefaultAsync(client => client.Id == id))
.WithName("GetClientById");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ermiya Eskandary |
