简体   繁体   中英

Retrieving Response Body from HTTP POST

I'm POSTing to API that is returning a 409 response code along with a response body that looks like this:

    { 
       "message": "Exception thrown.",
       "errorDescription": "Object does not exist"
    }

How can I pull out the Response Body and deserialize it?

I am using HttpClient:

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:60129");

    var model = new Inspection
    {
        CategoryId = 1,
        InspectionId = 0,
        Descriptor1 = "test descriptor 121212",
        Name = "my inspection 1121212"
    };

    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(model);
    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

    var result = client.PostAsync("api/Inspections/UpdateInspection", stringContent);

    var r = result.Result;

I seems like such a common thing to do, but I'm struggling to find where the data is in my result.

You can use ReadAsAsync<T> on the content of the response to a concrete type or ReadAsStringAsync to get the raw JSON string.

Would also suggest using Json.Net for working with the JSON.

var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);

var json = await response.Content.ReadAsStringAsync();

A concrete response model can be created

public class ErrorBody { 
   public string message { get; set; }
   public string errorDescription { get; set; }
}

and used to read responses that are not successful.

var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);

if(response.IsSuccessStatusCode) {
    //...
} else {
    var error = await response.Content.ReadAsAsync<ErrorBody>();

    //...do something with error.
}

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