我正在尝试在我的网络 API 中使用 [FromQuery],但我不确定如何使用它。
这是 Controller 中的 GetAllBooks() 方法:
[HttpGet]
[Route("api/v1/ShelfID/{shelfID}/BookCollection")]
public async Task<IActionResult> GetAllBooks(string shelfID, [FromQuery] Book bookinfo)
{
//do something
}
这是 Book 模型类:
public class Book
{
public string ID{ get; set; }
public string Name{ get; set; }
public string Author { get; set; }
public string PublishDate { get; set; }
}
我很困惑这是否是使用 [FromQuery] 的正确方法。我以为网址是
https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection/IActionResult?ID="123"&Name="HarryPotter"
但是断点没有命中我的 Controller 方法,所以我在想可能是 URL 不正确。有什么建议么?谢谢!
最佳答案
当您通过这样的属性显式定义路由时,方法的名称和返回类型将被完全忽略。 IActionResult
不应该存在。
正确的 URL 应该是:https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection?ID="123"&Name="HarryPotter"
此外,查询字符串绑定(bind)仅适用于基本类型(字符串、整数等)。要将类绑定(bind)到查询字符串,您需要一个自定义模型绑定(bind)器,这非常复杂。
最好只显式声明要传入的属性:
public async Task<IActionResult> GetAllBooks(string shelfID,
[FromQuery] string ID,
[FromQuery] string Name)
关于c# - ASP.NET 核心 : [FromQuery] usage and URL format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49741284/