【问题标题】:JSON data missing in the response body of a REST queryREST 查询的响应正文中缺少 JSON 数据
【发布时间】: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);

标签: c# json rest get


【解决方案1】:

只需返回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);
}

【讨论】:

  • 你应该跳过 JsonConvert 直接使用return OK(list);
  • @JasonC,是的,你是对的。您可以直接返回列表。简单易行。
  • 感谢 Krishna 和 Jason 的回答!此更改解决了我的问题。但是,我想问是否有一种方法可以使用 HttpResponseMessage 或任何其他可以访问 HTTP 消息的每个标头的构造来发送列表。
  • @SumeetPannu,希望 stackoverflow.com/questions/54136488/… 有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 2017-03-29
相关资源
最近更新 更多