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

Posted

技术标签:

【中文标题】ASP.NET Core:[FromQuery] 用法和 URL 格式【英文标题】:ASP.NET Core: [FromQuery] usage and URL format 【发布时间】:2018-09-19 08:15:56 【问题描述】:

我正在尝试在我的 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"&amp;Name="HarryPotter"

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

【问题讨论】:

【参考方案1】:

当您通过类似的属性显式定义路由时,方法的名称和返回类型将被完全忽略。 IActionResult 不应该在那里。

正确的网址是:https://localhost:xxxxx/api/v1/ShelfID/shelfID/BookCollection?ID="123"&amp;Name="HarryPotter"

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

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

public async Task<IActionResult> GetAllBooks(string shelfID, [FromQuery] string ID, [FromQuery] string Name)

【讨论】:

您还可以使用 [FromQuery] 绑定到复杂对象,例如public async Task&lt;IActionResult&gt; Get([FromQuery] MyFilterModel _filters)参考这个链接:tutorialsteacher.com/webapi/parameter-binding-in-web-api

以上是关于ASP.NET Core:[FromQuery] 用法和 URL 格式的主要内容,如果未能解决你的问题,请参考以下文章