JRockFL
asked on
Async and await with MVC and Web Api
Please see the following code. I want to make sure I'm implementing async and await correctly. This concept is new to me.
I'm using MVC to consume a Web Api service.
I'm using MVC to consume a Web Api service.
// GET: Products/ProductsByCategory/5
public async Task<ActionResult> ProductsByCategory(int id)
{
string url = string.Format("{0}api/categories/{1}/products", baseUrl, id);
Service<GetProductsByCategoryID> service = new Core.Service<GetProductsByCategoryID>(url);
return PartialView(await service.GetListAsync());
}
public async Task<List<T>> GetListAsync()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
return JsonConvert.DeserializeObject<List<T>>(
await client.GetStringAsync(url)
);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you for your replies.
Also, thank you for the suggestion regarding HttpClient and being reused. Most of the examples I have seen use the using block.
But now I have located some topics regarding HttpClient and re usability.
Also, thank you for the suggestion regarding HttpClient and being reused. Most of the examples I have seen use the using block.
But now I have located some topics regarding HttpClient and re usability.
One thing to note--slightly off-topic--is that HttpClient is designed to be reused for multiple requests. So rather than wrapping your instance in a using you might consider widening the scope of that variable such that you can re-use the single instance across requests.