从 PostAsJsonAsync 获取响应 [英] Get response from PostAsJsonAsync
问题描述
我有这行代码
var response = new HttpClient().PostAsJsonAsync(posturi, model).Result;
Called WebAPI 控制器返回一个 bool 以确保对象已保存,但我如何返回该 bool 响应?
The Called WebAPI controller returns a bool to make sure the object was saved, but how do I return that bool response?
推荐答案
继续从内容中获取:
var httpClient = new HttpClient();
var response = httpClient.PostAsJsonAsync(posturi, model).Result;
bool returnValue = response.Content.ReadAsAsync<bool>().Result;
但是,对于快速获得结果的方法来说,这确实是一种天真的方法.PostAsJsonAsync
和 ReadAsAsync
不是这样设计的,它们旨在支持 async await
编程,所以你的代码应该是:
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>();
此外,不要使用标志来检查对象是否已保存,而应使用 HTTP 代码通过返回 200 OK
来确定保存成功.
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 获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!