Using async/await and returning Task<HttpResponseMessage> From ASP.NET Web API Methods
Async and await are perfectly acceptable in ASP.NET. Here's a Scott Handselman video demoing it: http://www.asp.net/vnext/overview/aspnet/async-and-await
"Also would I have the same effect if I returned Task<string>
rather than Task<HttpResponseMessage>
?"
Not really sure what you mean by this. The Task is like a container for the object, so a Task<string>
would contain your string result and a Task<HttpResponseMessage>
would contain your HttpResponseMessage result... Is that what you mean? I think either method is perfectly acceptable. If you just need the string, then go with that. No point in returning more than you need.
as alternative:
public static async Task<string> CallGET(string requestUri, string id = "")
{
string responseData;
using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Uri.TryCreate(new Uri(baseURI), $"{requestUri}{(string.IsNullOrEmpty(id) ? string.Empty : $"/{id}")}", out Uri fullRequestUri);
using (var response = await client.GetAsync(fullRequestUri))
{
responseData = await response.Content.ReadAsStringAsync();
}
return responseData;
}
}
and call would be:
var getListUsersResult = Utils.CallGET($"/v1/users").Result;
var resultset= JsonConvert.DeserializeObject(getListUsersResult, typeof(List<UsersDTO>)) as List<UsersDTO>;
UserDTO r = users.Where(d => d.Name.ToLower().Contains("test")).FirstOrDefault();
and another call for one item:
var getUser = Utils.CallGET($"/v1/users", $"{USER_ID}").Result;
var getUserResponse = JsonConvert.DeserializeObject(getUser, typeof(UserDTO)) as UserDTO;