Link to home
Start Free TrialLog in
Avatar of JRockFL
JRockFLFlag for United States of America

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.

        // 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)
                );
            }
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
P.S.

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.
Avatar of JRockFL

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.