ASP.NET Core:[FromQuery]用法和URL格式

问题描述 投票:0回答:1

我正在尝试在我的 Web API 中使用

[FromQuery]
,但我不知道如何使用它。

这是控制器中的

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"

但是断点没有击中我的控制器方法,所以我想也许 URL 不正确。有什么建议么?谢谢!

c# asp.net-core asp.net-core-webapi
1个回答
52
投票

当您通过这样的属性显式定义路由时,方法的名称和返回类型将被完全忽略。

IActionResult
不应该在那里。

正确的网址是:

https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection?ID="123"&Name="HarryPotter"

此外,查询字符串绑定仅适用于原始类型(字符串、整数等)。要将类绑定到查询字符串,您需要一个自定义模型绑定器,这非常复杂。

最好直接显式声明要传入的属性:

public async Task<IActionResult> GetAllBooks(string shelfID,
                                             [FromQuery] string ID, 
                                             [FromQuery] string Name)
© www.soinside.com 2019 - 2024. All rights reserved.