gpt4 book ai didi

c# - 使用 C# 反序列化来自 Web Api 的 BadRequest 响应的问题

转载 作者:行者123 更新时间:2023-11-30 18:12:55 25 4
gpt4 key购买 nike

我有一个 web api,当用户注册失败时返回以下 json:

{
"$id":"1",
"Message":"The request is invalid.",
"ModelState": {
"$id":"2",
"": {
"$id":"3",
"$values": ["Name username@gmail.com is already taken."]
}
}
}

我已经尝试了各种方法在 C# 中反序列化它,以便在没有任何运气的情况下向用户显示错误消息。

这是我尝试过的事情之一:

https://www.codeproject.com/Articles/825274/ASP-NET-Web-Api-Unwrapping-HTTP-Error-Results-and?msg=5222750

如有任何帮助,我们将不胜感激。

提前致谢

最佳答案

试试这个:

定义以下类:

class WebApiResponse
{
public string Message { get; set; }
public Dictionary<string, IList<string>> ModelState { get; set; }
}

然后使用 Newtonsoft.Json 库将 json 响应反序列化为 WebApiResponse 类的实例:

var jsonFromWebApiResponse = @"{""$id"":""1"",""Message"":""The request is invalid."",""ModelState"":{""$id"":""2"","""":{""$id"":""3"",""$values"":[""Name username@gmail.com is already taken.""]}}}";

var webApiResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<WebApiResponse>(jsonFromWebApiResponse);

foreach (var modelState in webApiResponse.ModelState)
{
foreach (var innerMessage in modelState.Value)
{
// Do something with the messages inside ModelState...
}
}

关于c# - 使用 C# 反序列化来自 Web Api 的 BadRequest 响应的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607757/

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