如何调用异步任务函数?

时间:2017-07-18 12:12:01

标签: asp.net-web-api async-await

我的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);
    }

我的代码web api正常运行,如下所示

enter image description here

但是我在调​​用函数时遇到错误,如下所示

enter image description here

我不确定为什么我会收到此错误,尝试使用Google搜索但无法找到解决方案。

1 个答案:

答案 0 :(得分: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();**
相关问题