简体   繁体   中英

problem deserializing BadRequest response from Web Api using c#

I have a web api that returns the following json when user registration fails:

{
    "$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.

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

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#. Not tested on c# but works on 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:

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...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM