DEV Community

Cover image for How to use HttpClient in ASP.NET MVC to consume an ASP.NET Web API REST service?
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

How to use HttpClient in ASP.NET MVC to consume an ASP.NET Web API REST service?

Ang What is REST Services?

REST services stand for Representational State Transfer. It is a lightweight, scalable and maintainable service that is built on REST architecture which is used to access and manipulate the resources identified through URL.

Prerequisites

To consuming Web API REST services first you need to create a Web API REST service and then publish and host the web service on the IIS server you created. After hosting the web service then consuming this API in the client application.

After creating and hosting web API Now we start consuming Web API REST service in our ASP.NET MVC application step by step.

Create MVC Application

Open Microsoft Visual studio. Click on File followed by NEW, then click on the project, select ASP.NET web application, give an appropriate name and click OK.

After clicking OK, the following window will appear. select Empty and MVC Options then click OK.

Image description

This step creates the simple ASP.NET MVC application without any controller and view. This is how your project should be like in solution Explore.

Image description

Now we need to Install the HttpClient library from NuGet

We use the HttpClient to consume our Hosted Web API REST service. So for this, we need to install the HttpClient library from NuGet Package Manager.

Right-click on the Application name and click on Manage NuGet Package.

Read More: Building A Restful Api In Asp.net Mvc 5

What is HttpClient?

HttpClient class provide a base class that is used to send HTTP request and receive HTTP response resources.

HttpClient sends and receives data from Web API URL which is hosted on the local IIS server.HttpClient can process multiple requests concurrently.

Image description

Search System.Net.Http and click on the install button. It will be taking few seconds for installing this Library.

Now we need to Install WebAPI.Client library from NuGet
Search Microsoft.AspNet.WebApi.client and click on the install button. It will be taking few seconds for installing this Library. We need to install all necessary packages to consume Web API REST services in our application.

Image description

Now, we have installed all the necessary packages require to consume Web API REST services in web applications.

Create Model Class

Now, we need to create a model class inside the model folder. Right-click on the Model folder and add a class named Employee. cs.

Employee.cs file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ConsumingWebAPI.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string city { get; set; }
public string EmailID { get; set; }
public long Salary { get; set; }
}
}

Enter fullscreen mode Exit fullscreen mode

Right-click on the controller folder, click on Add and select controller. select the Empty template from the controller list and give the appropriate name to the controller.

Image description

In my hosted web API RESET services, I have included two methods, as given below

  • GetAllEmployee
  • GetEmployeeById

GetAllEmployee method handles HttpGET.GetEmployeeById handles HttpPOST this method takes employee id as a parameter in the method.

In the controller method, we are going to call the GetAllEmployee method that returns all the details employee, my hosted web API REST service base URL is http://192.168.45.1:6350/ and call the methods as per your requirement specified from our hosted web API REST services. This URL be a base URL after the URL it will be the API controller name and API method same as the following.

http://192.168.45.1:6350/api/Employees/GetAllEmployee

In the preceding URL

  • http://localhost:51910 This is the base address of my web API, It will be different as per your server.
  • API It is then used to differentiate between an MVC controller request Web API controller request.
  • Employees are the controller name of Web API.
  • GetAllEmployee is the Web API method that returns the list of all employees.
  • GetEmployeeById is the web API method that returns a record of an employee using employee id

Searching for Reliable .NET Development Company? Your Search ends here.

Add the following code inside the controller.

EmployeeController


using ConsumingWebAPI.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace ConsumingWebAPI.Controllers
{
public class EmployeeController: 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();
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);
}
}
public async Task<actionresult> Details()
{
List<employee> EmpDetails = 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/GetEmployeeById");
if (Res.IsSuccessStatusCode)
{
var record = Res.Content.ReadAsStringAsync().Result;
EmpDetails = JsonConvert.DeserializeObject<list<employee>>(record);
}
return View(EmpDetails);
}
}
}
}
</list<employee></employee></employee></actionresult></list<employee></employee></employee></actionresult>         

Enter fullscreen mode Exit fullscreen mode

Create View

Now, we need to create a view. Right-click on the index method, click on Add view and give the name for it then select model class for the view. Select list in the template, it will create the required index view.

Index.cshtml

@model IEnumerable<consumingwebapi.models.employee>
@{
ViewBag.Title = "Index";
}<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")</p>
@foreach (var item in Model) {

}
<table class="table"><tbody><tr><td></td></tr></tbody><tbody><tr><td></td><th>
@Html.DisplayNameFor(model => model.Name)</th><td></td><th>
@Html.DisplayNameFor(model => model.city)</th><td></td><th>
@Html.DisplayNameFor(model => model.EmailID)</th><td></td><th>
@Html.DisplayNameFor(model => model.Salary)</th><td></td><th></th><td></td></tr><tr><td></td><td>
@Html.DisplayFor(modelItem => item.Name)</td><td></td><td>
@Html.DisplayFor(modelItem => item.city)</td><td></td><td>
@Html.DisplayFor(modelItem => item.EmailID)</td><td></td><td>
@Html.DisplayFor(modelItem => item.Salary)</td><td></td></tr></tbody></table>
</consumingwebapi.models.employee>         

Enter fullscreen mode Exit fullscreen mode

we create a detailed view for getting employees using id.

Detail.cshtml

<xmp>
@model ConsumingWebAPI.Models.Employee
@{
ViewBag.Title = &quot;Details&quot;;
}
<h2>Details</h2>
<div>
<h4>Employee</h4>
<hr />
<dl class="dl-horizontal">
<dt>@Html.DisplayNameFor(model => model.Name)</dt>
<dd>@Html.DisplayFor(model => model.Name)</dd>
<dt>@Html.DisplayNameFor(model => model.city)</dt>
<dd>@Html.DisplayFor(model => model.city)</dd>
<dt>@Html.DisplayNameFor(model => model.EmailID)</dt>
<dd>@Html.DisplayFor(model => model.EmailID)</dd>
<dt>@Html.DisplayNameFor(model => model.Salary)</dt>
<dd>@Html.DisplayFor(model => model.Salary)</dd>
</dl>
</div>
<p>@Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</p>
</xmp>         

Enter fullscreen mode Exit fullscreen mode

We have done all the coding.

Now, run the application and you can observe the expected result.

Conclusion

Here in this blog, we have learned how to consume REST Web API Services using HttpClient step by step using Asp.Net MVC. This helps you to comprehend REST API services, and how it is hosted before consuming services for the application.

Top comments (0)