2012-11-04 28 views
18

我打電話使用的HttpClient從.Net框架4.5調用使用的HttpClient從Web API操作

的示例代碼如下運行一個ASP.Net MVC 4的Web API項目內外部服務(外部HTTP服務忽略返回值,因爲這是示例代碼來測試調用外部服務):

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

而在私有方法確實工作,我有問題的代碼是控制器的get()調用的GetResponse()但它並不等待結果,而是立即執行返回結果= null。

我一直在使用一個簡單的同步調用與Web客戶端也試過如下:

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

     var client = new WebClient(); 

     result = client.DownloadString(_address); 

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

工作正常。

我在做什麼錯?爲什麼Get()不等待異步樣本中的私有方法完成?

+0

你不需要用await調用GetResponse()嗎?否則,不會等待該方法完成...並且您的控制器操作將直接完成,結果仍然爲空。 – jishi

+0

是的,但我沒有意識到我可以將Get()標記爲使用await所需的async。 – Redeemed1

回答

30

啊哈,我需要做以下(返回任務而不是無效):

// 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()操作異步這是什麼讓我等待外部電話。

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

+0

就是我最近3天以來一直在尋找的東西!簡單一旦你知道它:)最短和最有效的答案。 –

0

用用戶名和密碼調用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)); 

      } 
} 
+0

卡蘭,感謝您在這裏的努力,但這與問題無關。您的回覆與身份驗證有關,該問題與未經身份驗證的API有關的異步任務相關 – Redeemed1

相關問題