Why is Task<HttpResponseMessage> not awaitable in my project?

此生再无相见时 提交于 2019-12-22 06:59:56

问题


I have a project that is targeting the .NET 4 framework and I've created a method which updates data in a database. The method itself also uses a flag (runAsync) to determine whether it should run asynchronously or not. I'm getting an error that 'System.Threading.Tasks.Task< HttpResponseMessage > is not awaitable' but I am using this same code in another application and it works fine. What am I doing wrong, or what am I missing to get this to work?

Here is the code:

public static async Task<object> UpdateData(SecureData data, string userAgent, bool runAsync)
{
    object result;

    try
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri(_configUri);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = runAsync
                                                ? await client.PutAsJsonAsync(String.Format("api/securedata/update/{0}", data.Token), data)
                                                : client.PutAsJsonAsync(String.Format("api/securedata/update/{0}", data.Token), data).Result;

            result = runAsync
                            ? await response.Content.ReadAsAsync<object>()
                            : response.Content.ReadAsAsync<object>().Result;

            response.EnsureSuccessStatusCode();
        }
    }
    catch (HttpRequestException ex)
    {
        throw new HttpRequestException(ex.Message, ex.InnerException);
    }

    return result;
}

回答1:


You cannot use async/await on ASP.NET 4.0. You must upgrade to 4.5.




回答2:


Install Async

Tools --> NuGet --> Packet manager console

run below code

Install-Package Microsoft.Bcl.Async -Version 1.0.168 

Ref: https://www.nuget.org/packages/Microsoft.Bcl.Async



来源:https://stackoverflow.com/questions/25043738/why-is-taskhttpresponsemessage-not-awaitable-in-my-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!