无法创建任务<httpresponsemessage>&#34; await&#34; </httpresponsemessage>

时间:2014-06-02 10:59:32

标签: c# asynchronous httpclient async-await

我正在尝试在我的web api包装器中编写一个方法。我想使用“async / await”功能,以便UI不会被阻止。下面是web api包装器中的代码片段。

    public static async Task Get<T>(Dictionary<string, string> paramDictionary, string controller)
    {
        try
        {
            string absoluteUrl = BaseUrl + controller + "?";
            absoluteUrl = paramDictionary.Aggregate(absoluteUrl,
                (current, keyValuePair) => current + (keyValuePair.Key + "=" + keyValuePair.Value + "&"));
            absoluteUrl = absoluteUrl.TrimEnd('&');

            using (HttpClient client = GetClient(absoluteUrl))
            {
                HttpResponseMessage response = await client.GetAsync(absoluteUrl);
                return await response.Content.ReadAsAsync<T>();
            }
        }
        catch (Exception exception)
        {
            throw exception;
        }
    }

问题是我在下面的语句中遇到编译器错误。

HttpResponseMessage response = await client.GetAsync(absoluteUrl);

它说"Type System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> is not awaitable"。经过多次搜索后,我无法摆脱这个错误。我出错的任何想法?请帮忙。

3 个答案:

答案 0 :(得分:5)

据我所知,这是因为您的方法返回Task,而不是Task<T>。所以你不能做return await response.Content.ReadAsAsync<T>()。更改签名以返回Task<T>

public static async Task<T> Get<T>(...)

答案 1 :(得分:1)

嗯......我做了以下工作来进行编译。

  1. 为system.net.http.formatting extension dll
  2. 添加web api 2.2

    enter image description here

    1. 将方法签名从Task更改为Task<T>
    2. 祝你好运!

答案 2 :(得分:0)

更新Microsoft.Bcl.Build Nuget包对我有用。

相关问题