gpt4 book ai didi

c# - 如何在 C# (.NET Core 3.1) 中处理 POST 请求中的 JSON 数据

转载 作者:行者123 更新时间:2023-11-30 21:26:27 25 4
gpt4 key购买 nike

以前(在 .Net Core 2.1 中)我使用以下方法成功处理了 JSON 数据

[HttpPost]
[Route("sendJsonData")]
public JObject saveTemplate(JObject jsonString)
{

string templateName = (string)jsonString.SelectToken("templateName");
string filePathAndName = "D:\\" + "templates\\" + templateName + ".txt";

using (StreamWriter file = File.CreateText(@filePathAndName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, jsonString);
}

return jsonString;
}

但是当我使用 .Net Core 3.1 创建相同的方法时。它无法显示 JObject 的一些错误。我从下面的代码中获取 JSON

onSubmit() {
this.http.post("https://localhost:44350/ReportAPI/sendJsonData", this.surveyForm.value)
.subscribe(
data => console.log("success!", data),
error => console.error("couldn't post because", error)
);
}

错误如下(Postman 的回复)

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|6e209814-4dd7396cc2dfa182.",
"errors": {
"$": [
"The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Newtonsoft.Json.Linq.JToken]. Path: $ | LineNumber: 0 | BytePositionInLine: 14."
]
}
}

JSON

{  
"templateName":"BFS Survey",
"surveyQuestions":[
{
"questionTitle":"Name",
"questionType":"Text",
"questionGroup":{

}
},
{
"questionTitle":"Age",
"questionType":"Number",
"questionGroup":{

}
},
{
"questionTitle":"Gender",
"questionType":"Single choice",
"questionGroup":{
"options":[
{
"optionText":"Male"
},
{
"optionText":"Female"
},
{
"optionText":"Other"
}
],
"showRemarksBox":false
}
},
{
"questionTitle":"Skills",
"questionType":"Multi choice",
"questionGroup":{
"options":[
{
"optionText":"Java"
},
{
"optionText":"Angular"
},
{
"optionText":"Python"
},
{
"optionText":"R"
}
],
"showRemarksBox":false
}
}
]
}

代码使用 .Net Core 2.1 完美运行,但不适用于 3.1。请建议我如何解决这个问题。

最佳答案

为了从 ASP.NET Core 2.x 迁移到 3.0,请参阅 this link :

  • 添加对 Microsoft.AspNetCore.Mvc.NewtonsoftJson 的包引用
  • 在Startup.cs中,在方法ConfigureServices中添加:services.AddMvc().AddNewtonsoftJson();

关于c# - 如何在 C# (.NET Core 3.1) 中处理 POST 请求中的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59190056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com