Retrieving Response Body from HTTP POST
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.
}
ScottG
I am a software architect in Detroit, Michigan specializing in e-commerce on the Microsoft stack (ASP.NET MVC, WPF, WCF, SQL Server, and C#). I write software that integrates with Amazon MWS and AWS, Paypal, Google, Jet, and ChannelAdvisor among others.
Updated on June 04, 2022Comments
-
ScottG almost 2 years
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.
-
ScottG over 6 yearsIt was as simple as that, thank you so much. My problem was that I was looking at the response object inside the locals window in visual studio and just not seeing the data. Much appreciation!!