调用HttpClient的使用从Web API对外行动HTTP服务 [英] Calling external HTTP service using HttpClient from a Web API Action

查看:259
本文介绍了调用HttpClient的使用从Web API对外行动HTTP服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话使用的HttpClient从.Net框架4.5

I am calling an external service using HttpClient from within an ASP.Net MVC 4 Web Api project running on .Net Framework 4.5

样品code如下(忽略返回值,因为这是样品code测试调用外部服务):

The sample code is as follows (ignore the return values as this is sample code to test calling an external service):

public class ValuesController : ApiController
{
    static string _address = "http://api.worldbank.org/countries?format=json";
    private string result;

    // GET api/values
    public IEnumerable<string> Get()
    {
        GetResponse();
        return new string[] { result, "value2" };
    }

    private async void GetResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        result = await response.Content.ReadAsStringAsync();
    }
}

而在私有方法的code确实工作,我的问题是,该控制器的get()调用的GetResponse(),但它不等待结果,但不是立即执行与结果=空的回报。

While the code in the private method does indeed work the problem I have is that the Controller Get() calls the GetResponse() but it is not awaiting the result but instead immediately executes the return with result = null.

我还使用了Web客户端更简单的同步调用如下尝试:

I have also tried using a simpler synchronous call with a WebClient as follows:

 // GET api/values
    public IEnumerable<string> Get()
    {
        //GetResponse();

        var client = new WebClient();

        result = client.DownloadString(_address);

        return new string[] { result, "value2" };
    }

这工作得很好。

我是什么做错了吗?为什么的Get()不等待异步样品中的私有方法完成?

What am I doing wrong? Why does the Get() not await the private method completion in the async sample?

推荐答案

啊哈,我需要做以下(返回一个任务而不是无效):

Aha, I needed to do the following (return a Task rather then void):

 // GET api/values
    public async Task<IEnumerable<string>> Get()
    {
        var result = await GetExternalResponse();

        return new string[] { result, "value2" };
    }

    private async Task<string> GetExternalResponse()
    {
        var client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(_address);
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsStringAsync();
        return result;
    }

此外,我还没有意识到我可以标记的Get()操作异步这正是让我等待外部呼叫。

Also I hadn't realised I could mark the Get() operation as async which is what allowed me to await the external call.

感谢斯蒂芬·克利里为他的博客异步伺机其中指出我在正确的方向。

Thanks to Stephen Cleary for his blog post Async and Await which pointed me in the right direction.

这篇关于调用HttpClient的使用从Web API对外行动HTTP服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆