In many forum posts, developers and students have asked one common question, that is, how to use Web API REST Service in ASP.NET MVC application and how to make a call between them to exchange the information. So, considering this demand, I have decided to write this article to demonstrate how to consume ASP.NET Web API REST Service in ASP.NET MVC application with the help of HttpClient.
If you don't know what is Web API REST service and how to create, publish, host ASP.NET Web API REST Service, then please refer to my video as well as articles, using the following links. Also, follow the same sequence if you want to learn web API REST service from creating to hosting to consuming in client application.
In this article, we will use the same hosted Web API REST service to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.
Step 1 - Create MVC Application.
- "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
- Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK.
- After clicking, the following Window will appear. Choose empty project template and check on MVC option.
The preceding step creates the simple empty ASP.NET MVC application without Model, View, and Controller, The Solution Explorer of created web application will look like the following.
Step 2 - Install HttpClient library from NuGet
We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .
What is HttpClient ?
HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.
To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.
Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds, depending on your internet speed.
Step 3 - Install WebAPI.Client library from NuGet
This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.
Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.
Step 4 - Create Model Class
Now, let us create the Model class named Employee.cs or as you wish, by right clicking on
Models folder with same number of entities which are exposing by our
hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.
Employee.cs
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
-
- public string City { get; set; }
-
- }
Step 5 - Add Controller Class
Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.
After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller .
- GetAllEmployees (GET )
- GetEmployeeById (POST ) which takes id as input parameter
We are going to call GetAllEmployees method which returns the all employee details ,The hosted web api REST service base URL is http://192.168.95.1:5555/ and to call GetAllEmployees from hosted web API REST service, The URL should be Base url+api+apicontroller name +web api method name as following,
http://192.168.95.1:5555/api/Employee/GetAllEmployees
In the preceding url
- http://localhost:56290 Is the base address of web API service, It can be different as per your server.
- api It is the used to differentiate between Web API controller and MVC controller request .
- Employee This is the Web API controller name.
- GetAllEmployees This is the Web API method which returns the all employee list.
After modifying the code of Homecontroller class, the code will look like the following.
Homecontroller.cs
- using ConsumingWebAapiRESTinMVC.Models;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using System.Web.Mvc;
-
- namespace ConsumingWebAapiRESTinMVC.Controllers
- {
- public class HomeController : Controller
- {
-
- string Baseurl = "http://192.168.95.1:5555/";
- public async Task<ActionResult> Index()
- {
- List<Employee> EmpInfo = new List<Employee>();
-
- using (var client = new HttpClient())
- {
-
- client.BaseAddress = new Uri(Baseurl);
-
- client.DefaultRequestHeaders.Clear();
-
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
-
-
- HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");
-
-
- if (Res.IsSuccessStatusCode)
- {
-
- var EmpResponse = Res.Content.ReadAsStringAsync().Result;
-
-
- EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);
-
- }
-
- return View(EmpInfo);
- }
- }
- }
- }
I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .
Step 6 - Create strongly typed View
Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.
Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.
Index.cshtml
- @model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>
-
- @{
- ViewBag.Title = "www.compilemode.com";
- }
-
- <div class="form-horizontal">
-
- <hr />
- <div class="form-group">
-
-
- <table class="table table-responsive" style="width:400px">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.City)
- </th>
-
- </tr>
-
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.City)
- </td>
-
- </tr>
- }
-
- </table>
- </div>
- </div>
The preceding View will display all employees list . Now, we have done all the coding.
Step 7 - Run the Application
After running the Application, the employee list from hosted web API REST service will look like this.
I hope, from the above examples, you have learned how to consume Web API REST Service in ASP.NET MVC using HttpClient.
Note
- Download the Zip file of the Published code to learn and start quickly.
- This article is just guideline on how to consume Web API REST Service in ASP.NET MVC application using HttpClient .
- In this article, the optimization is not covered in depth; do it as per your skills.
Summary
I hope, this article is useful for all readers. If you have any suggestions, please mention them in the comments section.
Read more articles on ASP.NET