Get response from PostAsJsonAsync

后端 未结 5 2005
清歌不尽
清歌不尽 2020-12-08 07:47

I have this line of code

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

The Called WebAPI controller returns a bo

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 08:23

    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();
    

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

提交回复
热议问题