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

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

问题描述

我正在尝试在我的 web api 中使用 [FromQuery],但我不知道如何使用它.

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

 [HttpGet][Route("api/v1/ShelfID/{shelfID}/BookCollection")]公共异步任务GetAllBooks(字符串shelfID,[FromQuery] Book bookinfo){//做点什么}

这是 Book 模型类:

 公开课书{公共字符串 ID{ 获取;放;}公共字符串名称{获取;放;}公共字符串作者{获取;放;}公共字符串 PublishDate { 获取;放;}}

我很困惑这是否是使用 [FromQuery] 的正确方法.我以为网址是

<块引用>

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

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

解决方案

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

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

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

最好明确声明您要传入的属性:

public async TaskGetAllBooks(字符串shelfID,[FromQuery] 字符串ID,[FromQuery] 字符串名称)

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

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
            }

Here's the Book model class:

 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]. I thought the URL is

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. 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.

The correct URL would be: 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)

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

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