Reputation: 748
I have a PCl in which I want to make a async call usingg HttpClient. I coded like this
public static async Task<string> GetRequest(string url)
{
var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
HttpResponseMessage response = await httpClient.GetAsync(url);
return response.Content.ReadAsStringAsync().Result;
}
But await is showing error "cannot await System.net.http.httpresponsemessage" like message.
If I use code like this than everything goes well but not in async way
public static string GetRequest(string url)
{
var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
HttpResponseMessage response = httpClient.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
I just want that this method executes in async way.
This is the screen shot:
Upvotes: 1
Views: 2055
Reputation: 457217
Follow the TAP guidelines, don't forget to call EnsureSuccessStatusCode
, dispose your resources, and replace all Result
s with await
s:
public static async Task<string> GetRequestAsync(string url)
{
using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
If your code doesn't need to do anything else, HttpClient
has a GetStringAsync
method that does this for you:
public static async Task<string> GetRequestAsync(string url)
{
using (var httpClient = new HttpClient() { MaxResponseContentBufferSize = int.MaxValue })
return await httpClient.GetStringAsync(url);
}
If you share your HttpClient
instances, this can simplify to:
private static readonly HttpClient httpClient =
new HttpClient() { MaxResponseContentBufferSize = int.MaxValue };
public static Task<string> GetRequestAsync(string url)
{
return httpClient.GetStringAsync(url);
}
Upvotes: 6
Reputation: 142242
If you are using a PCL platform that supports .net4 then I suspect you need to install the Microsoft.bcl.Async nuget.
Upvotes: 1