C# 使用 HttpClient 从 Web API 操作调用外部 HTTP 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13222998/
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 07:47:52  来源:igfitidea点击:

Calling external HTTP service using HttpClient from a Web API Action

c#asp.net-web-apidotnet-httpclient

提问by Redeemed1

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

我在 .Net Framework 4.5 上运行的 ASP.Net MVC 4 Web Api 项目中使用 HttpClient 调用外部服务

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

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.

虽然私有方法中的代码确实有效,但我遇到的问题是控制器 Get() 调用了 GetResponse(),但它不是在等待结果,而是立即执行结果 = null 的返回。

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

我还尝试使用 WebClient 使用更简单的同步调用,如下所示:

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

        var client = new WebClient();

        result = client.DownloadString(_address);

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

which works fine.

这工作正常。

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

我究竟做错了什么?为什么 Get() 不等待异步示例中的私有方法完成?

采纳答案by Redeemed1

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

啊哈,我需要执行以下操作(返回一个 Task 而不是 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;
    }

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

此外,我还没有意识到我可以将 Get() 操作标记为异步,这允许我等待外部调用。

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

感谢 Stephen Cleary 的博客文章Async 和 Await,它为我指明了正确的方向。

回答by Karan Singh

With the username and password call Httpclient. In case of API required authentication.

用用户名和密码调用Httpclient。在 API 需要身份验证的情况下。

    public async Task<ActionResult> Index()
{

            const string uri = "https://testdoamin.zendesk.com/api/v2/users.json?role[]=agent";
            using (var client1 = new HttpClient())
            {
                var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("[email protected]:123456")));///username:password for auth
                client1.DefaultRequestHeaders.Authorization = header;
               var aa = JsonConvert.DeserializeObject<dynamic>(await client1.GetStringAsync(uri));

            }
}