【问题标题】:ASP.NET Web API: Multiple Custom Objects through Query StringASP.NET Web API:通过查询字符串的多个自定义对象
【发布时间】:2020-02-15 17:33:54
【问题描述】:

我正在开发一个 API,我想尝试通过我的查询字符串获取 sortfilterpagination 对象以 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 ..
        }
    }
}

这样,我所有的参数都是null

我看到了与此类似的其他关于自定义模型绑定的问题。我已经尝试过了,但我无法从查询字符串中获取值以尝试反序列化 JSON 数据。

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

【问题讨论】:

    标签: c# asp.net-core asp.net-web-api model-binding attributerouting


    【解决方案1】:

    您尝试对非原始对象执行的操作必须使用 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 ..
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多