在 Web api 的查询字符串中传递一个 json 对象?

pass a json object in query string for a web api?

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

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

因为这个 api 检索数据,我认为网络 API 需要是 GET。

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

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

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

Web API 设计上是否有更正式的方法?也许我应该使用 POST 而不是 GET?

第一种方式,你可以像下面这样传递查询字符串: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);
    }
}