0

I am trying to get the list of employees using Web API Get method in C# MVC and display in the view. But my list is coming null. I am not sure what i am missing. I am referring to this resource http://www.tutorialsteacher.com/webapi/consume-web-api-get-method-in-aspnet-mvc

Home Controller :

 namespace Sample.Controllers
 {
    public class HomeController : Controller
  {
    private readonly EmployeeDBEntities _db = new EmployeeDBEntities();

    public ActionResult Index()
    {
        IEnumerable<Employee> employees = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:62141/api/");
            //HTTP GET
            var responseTask = client.GetAsync("employee");
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IList<Employee>>();
                readTask.Wait();

                employees = readTask.Result;
            }
            else //web api sent error response 
            {
                //log response status here..

                employees = Enumerable.Empty<Employee>();

                ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
            }
        }
        return View(employees);
    }
 }
}

Employee API Controller :

namespace Sample.Controllers
{

public class EmployeeController : ApiController
{
    public IHttpActionResult GetAllEmployees()
    {
        IList<Employee> employees = null;

        using (var ctx = new EmployeeDBEntities())
        {
            employees = ctx.Employees.ToList<Employee>();
        }

        if (employees.Count == 0)
        {
            return NotFound();
        }

        return Ok(employees);
    }
  }
Nav
  • 71
  • 13
  • 1
    At which point in your code have you determined the null result? – Jasen Jan 17 '19 at 17:23
  • at this one var responseTask = client.GetAsync("employee"); – Nav Jan 17 '19 at 17:30
  • @Nav, because you are not `await`ing the `Task` that is returned by `GetAsync`. You will only get the result of that HTTP request in the next line, i.e. `responseTask.Wait();` And because you aren't assigning that to anything, the value is 'lost'. – ethane Jan 17 '19 at 17:31
  • @ethane how do I resolve this? – Nav Jan 17 '19 at 17:36
  • 1
    Excuse my hasty previous comment. I have a feeling that `var responseTask = client.GetAsync("employee");` is not at all the problematic line, you should still be getting your list out at `var result = responseTask.Result;` – ethane Jan 17 '19 at 17:38
  • 1
    No, I have added the breakpoint and checked. var result = responseTask.Result; is also null. after this line of code everything is null var responseTask = client.GetAsync("employee"); – Nav Jan 17 '19 at 17:46
  • 1
    Verify the api controller is returning results. Is that request URI supposed to route to the employee action? Follow this answer https://stackoverflow.com/a/15274773/2030565 rather than synchronously block with `.Wait()`. And read this https://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock. – Jasen Jan 17 '19 at 17:53

1 Answers1

0

You first should check the status code on you response. If it is NotFound then there was no results (the way your code is done). But your problem may be related to the fact that the result of ctx.Employees.ToList<Employee>(); is being disposed and terminated before the response is completed, but even that would give a DisposedException. You should consider adding You database context instance object in a IoC container with transient lifetime, and inject does dependencies to the controller constructor, because the request does not end when the action method ends.