本文介绍了获得PostAsJsonAsync响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这行code

VAR响应=新的HttpClient()PostAsJsonAsync(定位PostURI,模型)。结果;

 被叫的WebAPI控制器返回一个布尔值,以确保该对象被扑出,但我怎么返回布尔反应?

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?

推荐答案

继续从内容到获得:

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

不过,这确实是快速的方式来获得结果幼稚的做法。 PostAsJsonAsync ReadAsAsync 不是专做这个样子,它们被设计为支持异步的await 编程,所以你的code应该是:

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 codeS的通过返回 200 OK 确定储蓄是成功的。

这篇关于获得PostAsJsonAsync响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 20:51