我正在尝试在最小的 API 中使用 CreatedAtRoute
。
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);
});
我使用 EndpointName
属性来命名我在 POST 请求中引用的端点。但是,我得到了例外:
System.InvalidOperationException: 没有路由匹配提供的 values。
这很奇怪,因为 url 模式中只有一个参数 - id
。
一个小笔记
您可以使用 WithName
代替 [EndpointName]
属性:
app
.MapGet("/clients-m/{id:int}", async (int id, ClientsContext db) =>
await db.ClientsM.SingleOrDefaultAsync(client => client.Id == id))
.WithName("GetClientByIdAsync");
回答1
对于最少的 API,请尝试使用 https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.routingendpointconventionbuilderextensions.withname?view=aspnetcore-6.0#microsoft-aspnetcore-builder-routingendpointconventionbuilderextensions-withname-1(-0-system-string) 代替设置 EndpointNameAttribute
,即
app.MapGet("/clients/{id:int}", async (int id, ClientsContext db) =>
await db.Clients.SingleOrDefaultAsync(client => client.Id == id))
.WithName("GetClientById");