简体   繁体   English

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

[英]ASP.NET Core: [FromQuery] usage and URL format

I am trying to use [FromQuery] in my web api and I am not sure how to use it. 我试图在我的网络API中使用[FromQuery],我不知道如何使用它。

Here's the GetAllBooks() method in the controller: 这是控制器中的GetAllBooks()方法:

 [HttpGet]
 [Route("api/v1/ShelfID/{shelfID}/BookCollection")]
 public async Task<IActionResult> GetAllBooks(string shelfID, [FromQuery] Book bookinfo)
            {
               //do something
            }

Here's the Book model class: 这是Book模型类:

 public class Book
    {
        public string ID{ get; set; }
        public string Name{ get; set; }
        public string Author { get; set; }
        public string PublishDate { get; set; }
    }

I am confused about whether it is the correct way to use [FromQuery]. 我很困惑这是否是使用[FromQuery]的正确方法。 I thought the URL is 我以为URL是

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

But the break point is not hitting my controller method, so I was thinking maybe the URL is not correct. 但是断点并没有达到我的控制器方法,所以我想也许URL不正确。 Any suggestions? 有什么建议? Thanks! 谢谢!

The name of the method and return type are completely ignored when you define your route explicitly via attributes like that. 当您通过类似的属性显式定义路由时,将完全忽略方法的名称和返回类型。 IActionResult shouldn't be there. IActionResult不应该在那里。

The correct URL would be: https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection?ID="123"&Name="HarryPotter" 正确的URL将是: https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection?ID="123"&Name="HarryPotter"

Furthermore, query string binding only works out of the box for primitive types (string, int, etc). 此外,查询字符串绑定仅对原始类型(字符串,整数等)开箱即用。 To bind a class to a query string you'd need a custom modelbinder, which is quite involved. 要将类绑定到查询字符串,您需要一个非常复杂的自定义模型绑定器。

It would be better to just explicitly declare the properties you want to pass in: 最好只显式声明要传入的属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM