asp.net-core - 在 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?
解决方案
第一种方式,您可以传递如下查询字符串: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);
}
}
推荐阅读
- oracle - Oracle 中的全局非分区索引
- javascript - 使用轮子事件更改类
- bash - 如何在循环中追加新行\ n
- javascript - 如何防止显示的实际文件路径检查网络终端
- python - 如何检查某些输入是否属于 sympy 函数?
- android - 如何同时从本地电话簿和谷歌联系人中获取所有联系人?
- android - ConstraintLayout that should support portrait and landscape modes -with a button to toggle full screen
- javascript - 如何在不模拟 ActivatedRouteSnapshot 的情况下测试角度防护/解析器
- go - 如何在 Github 上设置我的 Golang 项目版本
- python - 使用 GoogleNews-vectors-negative300.bin 构建字典返回 ValueError: could not convert string to float