c# - Asp.net 核心无效 JSON
问题描述
asp.net
我在向我的服务器发送发布请求时遇到问题。
我的 Json 看起来像这样:
{
"Name":"NothingZeile224","FimDocument":"PHhkZjp4ZW5zY2hlbWEuMDEwMj4=","FimCodelistPicks":[]
}
当我通过 a 将其发送HttpRequestMessage
到Body
我的服务器时,我得到以下响应:
{
"errors": {
"": [
"Unexpected character encountered while parsing value: {. Path '', line 1, position 1."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|1db3b81f-4ca934b691097e16."
}
如果我删除 JSON 中的大括号,它看起来像这样:
"Name":"NothingZeile224","FimDocument":"PHhkZjp4ZW5zY2hlbWEuMDEwMj4=","FimCodelistPicks":[]
有用。
但我不明白为什么?有人有想法吗?
谢谢
编辑:
这是我的服务器代码:
[Produces("application/json")]
[ApiController]
public class MainController : ControllerBase
{
[HttpPost]
[Route("api/ConvertToCirali")]
public async Task<string> ConvertToCirali([FromBody] string PostSendFim)
{
try
{
PostModel pm = (PostModel)Newtonsoft.Json.JsonConvert.DeserializeObject(PostSendFim);
XDocument fim = XDocument.Parse(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(pm.FimDocument)));
string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(pm.FimCodelists);
string MyContent = null;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44398/api/FullCodelists"))
{
using (StringContent stringContent = new StringContent(Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonOutput)), Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
MyContent = await response.Content.ReadAsStringAsync();
}
}
}
}
List<MongoCodelist> ReturnedCodelists = new List<MongoCodelist>();
ReturnedCodelists = (List<MongoCodelist>)Newtonsoft.Json.JsonConvert.DeserializeObject(MyContent);
FormatterFimToCirali fftc = new FormatterFimToCirali(fim, ReturnedCodelists);
Debug.WriteLine("Hier steht der Text: " + fftc.CiraliFile.ToString());
return Convert.ToBase64String(Encoding.UTF8.GetBytes(fftc.CiraliFile.ToString()));
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
抱歉,如果它看起来有点奇怪,它是用于游戏文件的转换器
解决方案
您已将参数声明为字符串,因此您需要向其发送 JSON 字符串,而不是 JSON 对象。然后在您的代码中反序列化此字符串
PostModel pm = (PostModel)Newtonsoft.Json.JsonConvert.DeserializeObject(PostSendFim);
您可以跳过一个步骤,让框架为您进行反序列化。只需将参数类型更改为PostModel
而不是string
.
推荐阅读
- javascript - Siema carousel 不起作用我已将文件添加到我的 wp-includes 中
- excel - Excel 问题: Cell A2=F2 , A8=F3 我怎样才能做到这一点?
- visual-studio-code - 用于启动 EXE 并插入从 EXE 返回的文本的 VS Code 扩展
- c# - DontDestroyOnLoad 在改变场景时正在销毁对象
- tensorflow - 运行自动编码器时的Tensorflow set_seed错误
- reactjs - React.createElement 类型无效
- python-3.x - 有没有办法 ping 计算机的 IP 地址,以便在它们连接到我的服务器时在 GUI 中在线(或离线)显示它们?
- flutter - 滚动出现问题后如何在列表视图中获取小部件的 currentContext?
- javascript - 如何在不重新加载页面的情况下使用经度和纬度坐标动态更改谷歌地图上的位置点
- git - GIT:从两个分支创建文件的合并版本