2017-07-18 82 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();**