Asp.net Web Api通过查询字符串的多个自定义对象

问题描述 投票:0回答:1

我正在使用api,我想尝试通过json形式的查询字符串获取排序过滤器和分页对象。

当前,我正在使用以下命令调用我的api:

baseUrl/reviews?sort={"direction":"asc","field":"time"}&filters=[{"field":"rating","value":9}]&page={"page":1,"items":10}

我的控制器看起来像这样

namespace NewApi.Controllers
{
[Route("api/[controller]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        [HttpGet]
        public JsonResult Search([FromQuery(Name = "sort")] Sort sort, [FromQuery(Name = "Filters")] List<Filter> filters, [FromQuery(Name = "Page")] Page page)
        {
            ... getting data from db be here ..
        }
    }
}

有了这个,我所有的参数都为空。

[我看到了与此类似的其他问题,这些问题都讨论了自定义模型绑定,我已经尝试过,但是我无法从查询字符串中获取值来尝试反序列化json数据。

我看到的另一种解决方法只是传递一个json对象,然后在控制器中反序列化它,但是我仍然无法从查询字符串中获取任何数据。

提前感谢。

c# asp.net asp.net-core asp.net-web-api attributerouting
1个回答
0
投票

您要使用非原始对象进行的操作必须使用http请求的主体来完成。如果要在查询字符串中执行此操作,请坚持使用原语。

baseUrl/reviews?sortDirection=asc&sortField=time&filterField=rating&filterValue=9&page=1&items=10


[Route("api/[controller]")]
[ApiController]
public class ApiController : ControllerBase
{
    [HttpGet]
    public JsonResult Search(string sortDirection, string sortField, string filterField, string filterValue, int page, int items)
    // I would also recommend returning IHttpActionResult, much more robust
    {
        ... getting data from db be here ..
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.