In this article I will explain with an example, how to call (consume) Web API using HttpClient in ASP.Net Core MVC.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Model
Following CustomerModel class is used as the Model class. This class consists of the following properties.
The CustomerID field is decorated with Key attribute as it is declared as Primary Key in the Customers Table.
using System.ComponentModel.DataAnnotations;
public class CustomerModel
{
[Key]
publi cstring CustomerID { get; set; }
publi cstring ContactName { get; set; }
publi cstring City { get; set; }
}
Database Context
The very first step is to create an ASP.Net MVC Application and connect it to the Database using Entity Framework.
Once the Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using WebAPI_EF_MVC_Core.Models;
using Microsoft.EntityFrameworkCore;
namespace WebAPI_EF_MVC_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<CustomerModel> Customers { get; set; }
}
}
Adding the Web API
In order to add a Web API Controller, you will need to Right Click the Controllers folder in the Solution Explorer and select on Add and then New Item.
Now from the Add New Item window, choose the API Controller – Empty option as shown below.
Then give it a suitable name and click Add.
Web API Controller
The Database Context class is injected into the Web API Controller using Dependency Injection method.
The Web API Controller consists of a method named GetCustomers which accepts a string parameter i.e. name.
Note: This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpGet attribute which signifies that the method will accept HTTP GET requests.
The records of the Customers are fetched using Entity Framework and are filtered using the StartsWith function based on the value of the Name property.
Finally, the records are returned as Generic List Collection.
[Route("api/[controller]")]
[ApiController]
public class CustomerAPIController : ControllerBase
{
private DBCtx Context { get; }
public CustomerAPIController(DBCtx _context)
{
this.Context = _context;
}
[Route("GetCustomers")]
[HttpGet]
public List<CustomerModel> GetCustomers(string name)
{
return (from c in this.Context.Customers.Take(10)
where c.ContactName.StartsWith(name) || string.IsNullOrEmpty(name)
select c).ToList();
}
}
Namespaces
You will need to import the following namespaces in the Home Controller.
using System.Net.Http;
using Newtonsoft.Json;
Controller
The Controller consists of following two Actions method.
Action method for handling GET operation
Inside this Action method, the SearchCustomers method is called with empty string value as parameter and a Generic List of CustomerModel class objects is returned to the View.
Inside the SearchCustomers method, the URL of the Web API along with its Controller method and the value of the Name parameter is passed to the GetAsync method of the HttpClient class.
The GetAsync method of the HttpClient class calls the Web API’s Controller method i.e. the GetCustomers method and returns the JSON string which is then de-serialized to Generic List of CustomerModel class objects.
Action method for handling POST operation
This Action method is called when the Form is submitted.
The SearchCustomers method is called here too, but the difference is that the value of the TextBox received from the View is passed as parameter.
public class HomeController : Controller
{
// GET: Home
public IActionResult Index()
{
List<CustomerModel> customers = SearchCustomers("");
return View(customers);
}
[HttpPost]
public IActionResult Index(string name)
{
List<CustomerModel> customers = SearchCustomers(name);
return View(customers);
}
private static List<CustomerModel> SearchCustomers(string name)
{
List<CustomerModel> customers = new List<CustomerModel>();
string apiUrl = "https://localhost:44318/api/CustomerAPI";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(apiUrl + string.Format("/GetCustomers?name={0}", name)).Result;
if (response.IsSuccessStatusCode)
{
customers = JsonConvert.DeserializeObject<List<CustomerModel>>(response.Content.ReadAsStringAsync().Result);
}
return customers;
}
}
View
Inside the View, in the very first line the CustomerModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the Form, there is a TextBox and a Submit Button.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using WebAPI_EF_MVC_Core.Models
@model IEnumerable<CustomerModel>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<span>Name:</span>
<input type="text" name="name" />
<input type="submit" value="Search" />
</form>
<hr/>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads