簡體   English   中英

使用Web API Action中的HttpClient調用外部HTTP服務

[英]Calling external HTTP service using HttpClient from a Web API Action

我在.Net Framework 4.5上運行的ASP.Net MVC 4 Web Api項目中使用HttpClient調用外部服務

示例代碼如下(忽略返回值,因為這是測試調用外部服務的示例代碼):

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

雖然私有方法中的代碼確實可以解決我的問題,但是Controller Get()調用了GetResponse(),但是它沒有等待結果,而是立即執行帶有result = null的返回。

我也嘗試過使用WebClient進行更簡單的同步調用,如下所示:

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

        var client = new WebClient();

        result = client.DownloadString(_address);

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

哪個工作正常。

我究竟做錯了什么? 為什么Get()不等待異步樣本中的私有方法完成?

啊哈,我需要做以下事情(返回一個任務而不是空洞):

 // 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()操作標記為async,這是允許我等待外部調用的原因。

感謝Stephen Cleary的博客文章Async和Await ,它指出了我正確的方向。

用戶名和密碼調用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("test@gmail.com:123456")));///username:password for auth
                client1.DefaultRequestHeaders.Authorization = header;
               var aa = JsonConvert.DeserializeObject<dynamic>(await client1.GetStringAsync(uri));

            }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM