Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

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


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

How_to_use_HttpClient_in_ASP.NET_MVC_to_consume_an_ASP.NET_Web_API_REST_service

Table of Content

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.

Empty_MVC_Application

[Empty MVC Application]
 

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.

Project_Structure

[Project Structure]

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.

 
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.

Install_HttpClient_Library

[Install HttpClient Library]
 

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.

Install_WebApi_client_Library.webp

[Install WebApi client Library]
 

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; }

    }
}

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.

Empty_Controller

[Empty Controller]
 

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

  1. GetAllEmployee
  2. 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

  1. http://localhost:51910 This is the base address of my web API, It will be different as per your server.
  2. API It is then used to differentiate between an MVC controller request Web API controller request.
  3. Employees are the controller name of Web API.
  4. GetAllEmployee is the Web API method that returns the list of all employees. 
  5. 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 Index()
        {
            List EmpInfo = new List();
            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>(EmpResponse);
                }
                return View(EmpInfo);
            }
        }
        public async Task Details()
        {
            List EmpDetails = new List();
            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>(record);
                }
                return View(EmpDetails);
            }
        }
    }
}
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

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.city) @Html.DisplayNameFor(model => model.EmailID) @Html.DisplayNameFor(model => model.Salary)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.city) @Html.DisplayFor(modelItem => item.EmailID) @Html.DisplayFor(modelItem => item.Salary)

we create a detailed view for getting employees using id.

Detail.cshtml

@model ConsumingWebAPI.Models.Employee

@{
    ViewBag.Title = "Details";
}



<h2>Details</h2>

<div>
<h4>Employee</h4>

<hr />
<dl class="dl-horizontal">
	<dt>@Html.DisplayNameFor(model =&gt; model.Name)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.Name)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.city)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.city)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.EmailID)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.EmailID)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.Salary)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.Salary)</dd>
</dl>
</div>

<p>@Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</p>

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.

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

How_to_use_HttpClient_in_ASP.NET_MVC_to_consume_an_ASP.NET_Web_API_REST_service

Table of Content

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.

Empty_MVC_Application

[Empty MVC Application]
 

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.

Project_Structure

[Project Structure]

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.

 
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.

Install_HttpClient_Library

[Install HttpClient Library]
 

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.

Install_WebApi_client_Library.webp

[Install WebApi client Library]
 

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; }

    }
}

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.

Empty_Controller

[Empty Controller]
 

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

  1. GetAllEmployee
  2. 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

  1. http://localhost:51910 This is the base address of my web API, It will be different as per your server.
  2. API It is then used to differentiate between an MVC controller request Web API controller request.
  3. Employees are the controller name of Web API.
  4. GetAllEmployee is the Web API method that returns the list of all employees. 
  5. 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 Index()
        {
            List EmpInfo = new List();
            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>(EmpResponse);
                }
                return View(EmpInfo);
            }
        }
        public async Task Details()
        {
            List EmpDetails = new List();
            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>(record);
                }
                return View(EmpDetails);
            }
        }
    }
}
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

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create")

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.city) @Html.DisplayNameFor(model => model.EmailID) @Html.DisplayNameFor(model => model.Salary)
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.city) @Html.DisplayFor(modelItem => item.EmailID) @Html.DisplayFor(modelItem => item.Salary)

we create a detailed view for getting employees using id.

Detail.cshtml

@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 =&gt; model.Name)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.Name)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.city)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.city)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.EmailID)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.EmailID)</dd>
	<dt>@Html.DisplayNameFor(model =&gt; model.Salary)</dt>
	<dd>@Html.DisplayFor(model =&gt; model.Salary)</dd>
</dl>
</div>

<p>@Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</p>

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.

Author Bio

Author

Author Name: Drashti varshani

Drasti varshani is an Asp.Net MVC fanatic. Her extensive knowledge in the subject and passion for helping others makes her exceptionally unique. She provides undeniable insights on Microsoft technologies for various platforms.