Reputation: 11121
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.
Upvotes: 3
Views: 22136
Reputation: 247088
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.
}
Upvotes: 10