2017-07-18 125 views
1

我上課AllWebApiOperations代碼如何調用異步任務功能?

public AllWebApiOperations(string apiURI) 
    { 
     client = new HttpClient(); 
     client.BaseAddress = new Uri(apiURI); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    } 

    public async Task<string> GetDataAsync(string route) 
    { 
     string result= string.Empty; 
     HttpResponseMessage response = await client.GetAsync(route); 
     if (response.IsSuccessStatusCode) 
     { 
      result = await response.Content.ReadAsAsync<string>(); 
     } 
     return result; 
    } 

我打電話這個按鈕點擊

string apiURI = @"http://localhost:35487/"; 
    private async void btnCallWebApi_Click(object sender, EventArgs e) 
    { 
     AllWebApiOperations op = new AllWebApiOperations(apiURI); 
     var result = await op.GetDataAsync(apiURI + "api/products/"); 
     Console.WriteLine(result); 
    } 

工作正常如下圖所示

enter image description here

我的代碼的Web API,但我在調用如下所示的函數時出錯:

enter image description here

我不知道爲什麼我得到這個錯誤,試過Google搜索但找不到解析。

回答

2

找到了答案:

public async Task<string> GetDataAsync(string route) 
{ 
    string result= string.Empty; 
    HttpResponseMessage response = await client.GetAsync(route); 
    if (response.IsSuccessStatusCode) 
    { 
     **result = await response.Content.ReadAsAsync<string>();** 
    } 
    return result; 
} 

,我應該使用

**result = await response.Content.ReadAsStringAsync();**