首页 > 解决方案 > 在 web api 的查询字符串中传递一个 json 对象?

问题描述

我有一个 Web API 方法,它接受 json 请求对象

{
    "FundCodes":["0DFOY"],
    "FromDate":"2021-04-01",
    "ToDate":"2021-05-01"
}

由于这个 api 检索数据,我认为 web API 需要是一个 GET。

但是,如果我这样做,我如何在查询字符串中传递上面的内容?

我知道 HTTP GET 确实有一个正文,我可以将参数放入,但我认为很多人反对使用正文的想法。那么如何将其放入查询字符串中?

我使用此站点对参数进行了 urlencode,但似乎我的 API 调用无法识别传递的参数。https://onlinejsontools.com/url-encode-json

那么在 Web API 设计上是否有更官方的方式呢?也许我应该使用 POST 而不是 GET?

标签: asp.net-coreasp.net-core-webapi

解决方案


第一种方式,您可以传递如下查询字符串:https://localhost:portNumber/WeatherForecast?fundcodes=aaa&fundcodes=bbb&fromDate=2021-04-01&toDate=2021-05-01.

模型:

public class TestModel
{
    public string[] FundCodes { get; set; }
    public string FromDate { get; set; }
    public string ToDate { get; set; }
}

控制器:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]

    public IActionResult Get([FromQuery]TestModel model)
    {
        return Ok(model);
    }
}

你会得到的结果:

在此处输入图像描述

第二种方式,您可以在浏览器中传递查询字符串,如下所示https://localhost:portNumber/WeatherForecast?json={"FundCodes":["0DFOY"],"FromDate":"2021-04-01","ToDate":"2021-05-01"}:浏览器将动态编码此 url 并传递给后端。

如果要手动发送编码的 url,则 url 应该是:https://localhost:portNumber/WeatherForecast?json={%22FundCodes%22:[%220DFOY%22],%22FromDate%22:%222021-04-01%22,%22ToDate%22:%222021-05-01%22}https://localhost:portNumber/WeatherForecast?json=%7B%22FundCodes%22%3A%5B%220DFOY%22%5D%2C%22FromDate%22%3A%222021-04-01%22%2C%22ToDate%22%3A%222021-05-01%22%7D.

控制器:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public IActionResult Get([FromQuery]string json)
    {
        var model = System.Text.Json.JsonSerializer.Deserialize<TestModel>(json);      
        return Ok(model);
    }
}

推荐阅读