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;
}
Install Async
Tools --> NuGet --> Packet manager console
run below code
Ref: https://www.nuget.org/packages/Microsoft.Bcl.Async
You cannot use
async
/await
on ASP.NET 4.0. You must upgrade to 4.5.