[英]problem deserializing BadRequest response from Web Api using c#
I have a web api that returns the following json when user registration fails: 我有一个web api,当用户注册失败时返回以下json:
{
"$id":"1",
"Message":"The request is invalid.",
"ModelState": {
"$id":"2",
"": {
"$id":"3",
"$values": ["Name username@gmail.com is already taken."]
}
}
}
I have tried all sorts of things to deserialize it in c# in order to display the error message to the user without any luck. 我已经尝试了各种各样的东西来在c#中反序列化它,以便向用户显示错误消息而没有任何运气。
Here's one on the things I have tried: 这是关于我尝试的事情的一个:
https://www.codeproject.com/Articles/825274/ASP-NET-Web-Api-Unwrapping-HTTP-Error-Results-and?msg=5222750 https://www.codeproject.com/Articles/825274/ASP-NET-Web-Api-Unwrapping-HTTP-Error-Results-and?msg=5222750
Any help on this will be greatly appreciated. 任何有关这方面的帮助将不胜感激。
Thank you in advance 先感谢您
I hope this solves your problem. 我希望这能解决你的问题。 I developed using vb.net and converted to c#.
我开发使用vb.net并转换为c#。 Not tested on c# but works on vb.net.
没有在c#上测试过,但在vb.net上有效。
class SurroundingClass
{
private void Button1_Click(object sender, EventArgs e)
{
var FullResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(WebResult);
Newtonsoft.Json.Linq.JObject lv2 = FullResponse.Item("ModelState");
Newtonsoft.Json.Linq.JObject lv3 = lv2.Item("");
string DisplayResponse = FullResponse.Item("Message") + " " + lv3.Item("$values").First;
MessageBox.Show(DisplayResponse);
}
public string WebResult()
{
return "{'$id':'1','Message':'The request is invalid.','ModelState':{'$id':'2','':{'$id':'3','$values':['Name username@gmail.com is already taken.']}}}";
}
}
Try this: 尝试这个:
Define the following class: 定义以下类:
class WebApiResponse
{
public string Message { get; set; }
public Dictionary<string, IList<string>> ModelState { get; set; }
}
Then use the Newtonsoft.Json
library to deserialize the json response as an instance of the WebApiResponse
class: 然后使用
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...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.