如何解决REST 查询的响应正文中缺少 JSON 数据
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing","Bracing","Chilly","Cool","Mild","Warm","Balmy","Hot","Sweltering","Scorching"
};
[HttpGet]
public HttpResponseMessage Get() //IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
WeatherForecast[] list = Enumerable.Range(1,5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),TemperatureC = rng.Next(-20,55),Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray();
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
var json = JsonConvert.SerializeObject(list);
msg.Content = new StringContent(json,System.Text.Encoding.UTF8,"application/json");
return msg;
}
}
使用 GET 查询 https://localhost:8675/weatherforecast
我在正文中收到以下响应:
{
"version": {
"major": 1,"minor": 1,"build": -1,"revision": -1,"majorRevision": -1,"minorRevision": -1
},"content": {
"headers": [{
"Key": "Content-Type","Value": ["application/json; charset=utf-8"]
}
]
},"statusCode": 200,"reasonPhrase": "OK","headers": [],"trailingHeaders": [],"requestMessage": null,"isSuccessstatusCode": true
}
Summaries 数组的数据以及温度未返回。 有人可以告知如何在 REST 查询的响应正文中发送 JSON 数据吗?
解决方法
只需返回返回类型为 Object
的 IActionResult
[HttpGet]
public IActionResult Get() //IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
WeatherForecast[] list = Enumerable.Range(1,5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),TemperatureC = rng.Next(-20,55),Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray();
//HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK);
//var json = JsonConvert.SerializeObject(list);
//msg.Content = new StringContent(json,System.Text.Encoding.UTF8,"application/json");
return Ok(list);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。