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?
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.
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.
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.
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 await
ed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With