Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get response from PostAsJsonAsync

I have this line of code

var response = new HttpClient().PostAsJsonAsync(posturi, model).Result; 

The Called WebAPI controller returns a bool to make sure the object was saved, but how do I return that bool response?

like image 847
Kai CriticallyAcclaimed Cooper Avatar asked Mar 04 '13 15:03

Kai CriticallyAcclaimed Cooper


People also ask

How do you read a PostAsJsonAsync response?

PostAsJsonAsync(posturi, model); bool returnValue = await response. Content. ReadAsAsync<bool>(); Also, instead of using a flag to check whether an object is saved or not, you should make use of HTTP codes by returning 200 OK to determine that saving is successfully.

What is PostAsJsonAsync?

PostAsJsonAsync<T>(HttpClient, Uri, T) Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON. PostAsJsonAsync<T>(HttpClient, Uri, T, CancellationToken) Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.


2 Answers

Continue to get from content:

var httpClient = new HttpClient(); var response = httpClient.PostAsJsonAsync(posturi, model).Result; bool returnValue = response.Content.ReadAsAsync<bool>().Result; 

But, this is really naive approach for quick way to get result. PostAsJsonAsync and ReadAsAsync is not designed to do like this, they are designed to support async await programming, so your code should be:

var httpClient = new HttpClient(); var response = await httpClient.PostAsJsonAsync(posturi, model); bool returnValue = await response.Content.ReadAsAsync<bool>(); 

Also, instead of using a flag to check whether an object is saved or not, you should make use of HTTP codes by returning 200 OK to determine that saving is successfully.

like image 140
cuongle Avatar answered Sep 17 '22 11:09

cuongle


The accepted answer is technically correct but blocks the current thread on calls to .Result. If you are using .NET 4.5 or higher, you should avoid that in almost all situations. Instead, use the equivalent asynchronous (non-blocking) version:

var httpClient = new HttpClient(); var response = await httpClient.PostAsJsonAsync(posturi, model); bool returnValue = await response.Content.ReadAsAsync<bool>(); 

Note that the method containing the above code needs to be marked async, and should itself be awaited.

like image 32
Todd Menier Avatar answered Sep 17 '22 11:09

Todd Menier