C# 从 PostAsJsonAsync 获取响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15205389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:29:27  来源:igfitidea点击:

Get response from PostAsJsonAsync

c#asp.net-mvc-4asp.net-web-api

提问by Kai CriticallyAcclaimed Cooper

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?

Called WebAPI 控制器返回一个 bool 以确保对象已保存,但如何返回该 bool 响应?

采纳答案by cuongle

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. PostAsJsonAsyncand ReadAsAsyncis not designed to do like this, they are designed to support async awaitprogramming, so your code should be:

但是,对于快速获得结果的方法来说,这确实是一种幼稚的方法。PostAsJsonAsync并且ReadAsAsync不是为了这样做而设计的,它们旨在支持async await编程,因此您的代码应该是:

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 OKto determine that saving is successfully.

此外,不要使用标志来检查对象是否已保存,您应该通过返回200 OK来使用 HTTP 代码来确定保存是否成功。

回答by Davin Tryon

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.

至少根据文档

回答by Stephen Lautier

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

由于它的异步操作不会立即执行.Result它的错误

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!

我希望它有帮助!

回答by Xaris Fytrakis

I used HttpStatusCode to check the result.

我使用 HttpStatusCode 来检查结果。

    public HttpStatusCode PostStaffPositions(Foo foo)
    {
        string uri = myapiuri;

        using (HttpClient httpClient = new HttpClient())
        {
            var response = httpClient.PostAsJsonAsync(uri, foo).Result;
            return response.StatusCode;
        }
    }

And then in Controller check it like this:

然后在控制器中像这样检查它:

   HttpStatusCode update = staffrest.PostStaffPositions(foo);
            if (update == HttpStatusCode.OK)
            {
               //Update Succeed
            }
            else
            {
                //Update Failed
            }

回答by Todd Menier

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:

接受的答案在技术上是正确的,但在调用.Result. 如果您使用 .NET 4.5 或更高版本,则几乎在所有情况下都应该避免这种情况。相反,使用等效的异步(非阻塞)版本:

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.

注意包含上述代码的方法需要被标记async,并且本身应该被await编辑。