I am making HTTP calls using System.Net.Http.HttpClient . It seems that all calls should be asynchronous.
Let's say I have a project structure: MVC Web Application β Business Layer β Data Layer
In the data layer, I make HTTP web API calls to return the data, and I end up using this function:
public async Task<IList<Product>> GetProducts() { HttpResponseMessage response = await client.GetAsync("api/products"); string data = await response.Content.ReadAsStringAsync(); IList<Product> products = JsonConvert.DeserializeObject<IList<Product>>(data); return products; }
this then goes to BusinessLayer:
public Task<IList<Product>> GetProducts(string name = null) { return _repository.GetProducts(name); }
Then, finally, in the MVC controller:
public IActionResult Index() { Task<IList<Product>> ProductsTask = _manager.GetProducts(); IList<Product> ProductsNonTask = products.Result.ToList(); return View(); }
Should I make each function return a list of Task<IList<Product>> types leading to my MVC controller? As you can see in the MVC, I must first retrieve the products first with the help of a task wrapped around them. The debugger looks strange when I look through the list of products through it. So, as you can see, I am converting them into a regular list of products.
I am wondering if this is the right thing to do so that all my functions return the type Task<IList<Product>> up to my MVC controller or if there is a workaround so that my functions can still return to the standard product list, but continue to use async features for HttpClient ?
UPDATE: something is wrong with this:
public IList<Product> GetProducts() { Task<HttpResponseMessage> response = client.GetAsync("api/products"); if (response.Result.IsSuccessStatusCode) { string data = response.Result.Content.ReadAsStringAsync().Result; IList<Product> products = JsonConvert.DeserializeObject<IList<Product>>(data); retVal = products; } }