How to call WEB API from ASP.NET MVC

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. When trying to work on it, the first to come to our mind is how to call Web Api method from MVC Web. Below code snippet helps us understand how to make a call from MVC Web to Web API and return a list of objects from Web API which is connected to the database

EmployeeController is the controller in the web and Index is the action which is called from the web. This method internally makes a call to the WebAPI and gets the resource by using the inbuilt HttpClient of System.Net.Http;

public class EmployeeController : Controller
    {
        HttpClient Client = new HttpClient();
        Uri BaseAddress = new Uri("http://localhost:14532/");
        public ActionResult Index()
        {
            Client.BaseAddress = BaseAddress; 
            HttpResponseMessage response = Client.GetAsync("EmployeeService/GetAllEmployeeDetails").Result; 
            if (response.IsSuccessStatusCode) 
            {
                var data = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result; 
                return View(data); 
            } 
            return View();
        }
    }

The requested resource URL from the above code will be as follows.

http://localhost:14532/EmployeeService/GetAllEmployeeDetails

One thought on “How to call WEB API from ASP.NET MVC

Leave a comment