我正在构建一个控制台 Web API 来与本地主机服务器通信,为他们托管电脑游戏和高分。每次我运行我的代码,我都会得到这个迷人的错误:
失败:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] 执行请求时发生未处理的异常。
System.NotSupportedException:不支持没有无参数构造函数、单一参数化构造函数或带有“JsonConstructorAttribute”注释的参数化构造函数的类型的反序列化。键入“System.Net.Http.HttpContent”。路径:$ | 行号:0 | 字节位置内线: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 对象以发送到数据库?
问题似乎是字符串 jasonHs...行,因为当我注释掉 ActionResult 方法的其余部分时,应用程序以完全相同的方式崩溃。