Get response from PostAsJsonAsync

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.


If you call the generic version, it should give you back the bool:

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

At least according to the docs.


Since its an Async operation don't immediately do .Result as its wrong

Instead you need to do it async by doing this:

    var httpClient = new HttpClient()

    var task = httpClient.PostAsJsonAsync(posturi, model)
                         .ContinueWith( x => x.Result.Content.ReadAsAsync<bool>().Result);

    // 1. GETTING RESPONSE - NOT ASYNC WAY
    task.Wait(); //THIS WILL HOLD THE THREAD AND IT WON'T BE ASYNC ANYMORE!
    bool response = task.Result

    // 2. GETTING RESPONSE - TASK ASYNC WAY (usually used in < .NET 4.5 
    task.ContinueWith( x => {
                              bool response = x.Result
                          });

    // 3. GETTING RESPONSE - TASK ASYNC WAY (usually used in >= .NET 4.5 
    bool response = await task;

NOTE: I just wrote them in here, so I didnt actually test them but more or less that's what you want.

I hope it helps!


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.