【发布时间】:2021-08-09 19:02:57
【问题描述】:
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 数据吗?
【问题讨论】:
-
你可以这样做
return Json(list);