如何从 HttpContent 检索 JSON 数据

How to retrieve JSON data from HttpContent

我正在构建一个控制台 Web API 以与本地主机服务器通信,为他们托管计算机游戏和高分。每次我 运行 我的代码,我都会得到这个迷人的错误:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request.

System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'System.Net.Http.HttpContent'. Path: $ | LineNumber: 0 | BytePositionInLine: 1.

这是我用来 post 数据库的方法。请注意,此方法不在控制台应用程序中。它位于 ASP.NET 核心 MvC 应用程序中,打开 Web 浏览器并侦听 HTTP 请求(可以来自控制台应用程序)。


[HttpPost]
public ActionResult CreateHighscore(HttpContent requestContent)
{
    string jasonHs = requestContent.ReadAsStringAsync().Result;
    HighscoreDto highscoreDto = JsonConvert.DeserializeObject<HighscoreDto>(jasonHs);

    var highscore = new Highscore()
    {
        Player = highscoreDto.Player,
        DayAchieved = highscoreDto.DayAchieved,
        Score = highscoreDto.Score,
        GameId = highscoreDto.GameId
    };

    context.Highscores.Add(highscore);
    context.SaveChanges();
    return NoContent();
}

我在纯 C# 控制台应用程序中发送 POST 请求,其中包含从用户输入收集的信息,但使用 Postman 发送 post 请求时结果完全相同 - 上述 NotSupportedException.

private static void AddHighscore(Highscore highscore)
{
    var jasonHighscore = JsonConvert.SerializeObject(highscore);
    Uri uri = new Uri($"{httpClient.BaseAddress}highscores");
    HttpContent requestContent = new StringContent(jasonHighscore, Encoding.UTF8, "application/json");

    var response = httpClient.PostAsync(uri, requestContent);
    if (response.IsCompletedSuccessfully)
    {
        OutputManager.ShowMessageToUser("Highscore Created");
    }
    else
    {
        OutputManager.ShowMessageToUser("Something went wrong");
    }
}

我是所有这些 HTTP 请求的新手,所以如果您在我的代码中发现一些明显的错误,我们将不胜感激。不过,最重要的问题是,我错过了什么,我如何从 HttpContent 对象中读取数据,以便能够创建一个 Highscore 对象发送到数据库?

问题似乎出在 string jasonHs... 行,因为当我注释掉 ActionResult 的其余部分时,应用程序以完全相同的方式崩溃方法。

根据您的代码,我们可以发现您使用 json 字符串数据(从 Highscore 对象序列化)从控制台客户端发送到 Web 的 HTTP Post 请求API 后端。

并且在您的操作方法中,您根据接收到的数据手动创建了一个 Highscore 实例,所以为什么不让您的操作接受一个 Highscore 类型参数,如下所示。然后 model binding system 将帮助自动将数据绑定到操作参数。

[HttpPost]
public ActionResult CreateHighscore([FromBody]Highscore highscore)
{
    //...