【问题标题】:ASP.NET Core: [FromQuery] usage and URL formatASP.NET Core:[FromQuery] 用法和 URL 格式
【发布时间】: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 可能不正确。有什么建议?谢谢!

【问题讨论】:

    标签: c# asp.net-core asp.net-core-webapi


    【解决方案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)
    

    【讨论】:

    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2021-11-28
    • 2018-12-17
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多