如何从 HttpContent

问题描述

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

失败: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] 执行请求时发生未处理的异常。

System.NotSupportedException:反序列化没有 无参数构造函数、单数参数化构造函数或 用“JsonConstructorAttribute”注释的参数化构造函数不支持。输入“System.Net.Http.HttpContent”。路径:$ | 行号:0 | BytePositionInLine: 1.

这是我用来发布到数据库方法。请注意,此方法不在控制台应用程序中。它位于 ASP.NET Core 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 发送请求时结果完全相同 - 上面的 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 API 后端发出 HTTP Post 请求。

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

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