Tejas Sutar
Tejas Sutar

Reputation: 777

Cannot make Task <HttpResponseMessage> "await"

I am trying to write a method in my web api wrapper. I want to make use of "async/await" feature so that UI doesn't get blocked. Below is the code snippet in the web api wrapper.

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

The problem is I get compiler error at the statement below.

HttpResponseMessage response = await client.GetAsync(absoluteUrl);

It says "Type System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> is not awaitable". After much searching I am not able to get rid of this error. Any ideas where I am going wrong? Please help.

Upvotes: 4

Views: 10268

Answers (3)

TheNameHobbs
TheNameHobbs

Reputation: 729

Updating the Microsoft.Bcl.Build Nuget package worked for me.

Upvotes: 0

Ryan Chu
Ryan Chu

Reputation: 1547

Hmmm... I did the following to get it compile.

  1. Add web api 2.2 for the system.net.http.formatting extension dll

enter image description here

  1. Change the method signature from Task to Task<T>

Good luck!

Upvotes: 1

noseratio
noseratio

Reputation: 61736

As far as I can tell, it's because your method returns Task, not Task<T>. So you cannot do return await response.Content.ReadAsAsync<T>(). Change the signature to return Task<T>:

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

Upvotes: 5

Related Questions