Are you building an ASP.NET MVC application and need to fetch data from a Web API? Look no further!
In this article, you’ll learn how to consume a Web API using the HttpClient
class in ASP.NET MVC with real examples and best practices.
✅ What You'll Learn
-
What is HttpClient
in .NET?
-
How to make GET requests to an API.
-
Deserialize JSON response into objects.
-
Display API data in an MVC view.
-
Full working code example.
🚀 Why Use HttpClient
?
The HttpClient
class is a part of the System.Net.Http
namespace and provides powerful capabilities to send HTTP requests and receive HTTP responses.
It supports
-
GET, POST, PUT, DELETE methods.
-
Asynchronous operations.
-
Custom headers and authentication.
🔧 Prerequisites
-
Visual Studio (2019 or newer recommended)
-
ASP.NET MVC project
-
A working Web API endpoint
-
NuGet package: Newtonsoft.Json
💡 Steps to Calling Web API in ASP.NET MVC
📌 Step 1. Create a Model
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
📌 Step 2. Create Your Controller
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;
using Newtonsoft.Json;
using YourApp.Models;
public class HomeController : Controller
{
string Baseurl = "https://yourapi.com/api/";
public async Task<ActionResult> Index()
{
List<Employee> EmpInfo = new List<Employee>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
// Set header to accept JSON
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// Call API
HttpResponseMessage Res = await client.GetAsync("Employee/GetAllEmployees");
// Check response
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);
}
}
return View(EmpInfo);
}
}
📌 Step 3. Create the View (Index.cshtml
)
@model IEnumerable<YourApp.Models.Employee>
<h2>Employee List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
</tr>
@foreach (var emp in Model)
{
<tr>
<td>@emp.Id</td>
<td>@emp.Name</td>
<td>@emp.Department</td>
</tr>
}
</table>
🛠 Notes and Best Practices
-
❗ Don't instantiate HttpClient
inside a loop or frequently. Consider reusing it with dependency injection.
-
💡 Always check for IsSuccessStatusCode
before using the response.
-
🔒 For APIs that require authentication (Bearer tokens, etc.), you can add headers:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
📦 Install Newtonsoft.Json
Install-Package Newtonsoft.Json
🏁 Conclusion
In this article, you learned how to use the HttpClient
class in ASP.NET MVC to consume a Web API. This approach is commonly used in enterprise apps where front-end MVC needs to pull data from microservices or external APIs.