Asp.net最小API查找用户名(字符串)



我想创建一个端点,它通过用户名(字符串)返回数据。

按id查找正在工作。它列出具有给定id的数据。

app.MapGet("/store/{id}", async (StoreDb db, int id) => await db.Stores.FindAsync(id))
.RequireAuthorization();

但是使用name(string)不起作用

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.FindAsync(name))
.RequireAuthorization();

模式:

Store {
id integer($int32)
name string
}
Json:

{
"id": 0,
"name": "string"
}

它不起作用因为FindAsync方法试图使用id找到记录,你只是在他的参数中传递不同的数据,你应该做的是像这样

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.Where(s => s.name == name).FirstOrDefault()).RequireAuthorization();

但是按名称检索会产生一些问题当有冗余的名称时所以你应该把FirstOrDefault()改为ToListAsync()这对这种情况比较好

app.MapGet("/store/{name}", async (StoreDb db, string name) => await db.Stores.Where(s => s.name == name).ToListAsync()).RequireAuthorization();

最新更新