ASP.NET Core:[FromQuery]用法和URL格式 [英] ASP.NET Core: [FromQuery] usage and URL format

查看:1164
本文介绍了ASP.NET Core:[FromQuery]用法和URL格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Web api中使用[FromQuery],但不确定如何使用它.

I am trying to use [FromQuery] in my web api and I am not sure how to use it.

这是控制器中的GetAllBooks()方法:

Here's the GetAllBooks() method in the controller:

 [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]是否是正确方法感到困惑.我以为网址是

I am confused about whether it is the correct way to use [FromQuery]. I thought the URL is

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

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

But the break point is not hitting my controller method, so I was thinking maybe the URL is not correct. Any suggestions? Thanks!

推荐答案

通过诸如此类的属性显式定义路由时,将完全忽略方法的名称和返回类型. IActionResult不应该在那里.

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.

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

此外,查询字符串绑定仅适用于基本类型(字符串,整数等)的开箱即用.要将类绑定到查询字符串,您需要一个自定义的modelbinder,它非常复杂.

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)

这篇关于ASP.NET Core:[FromQuery]用法和URL格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆