This tip will help you understand how to consume ASP.NET Web API from client side .NET.
Background
In some cases, you want to be using ASP.NET Web API endpoint with a client. For example, you want HTTP to give you GET
some data back or POST
/PUT
/DELETE
data to server. In this article, I use the HttpClient
to communicate between endpoint and client side.
First, we create project ASP.NET WEB API, add NORTHWIND
db, add Nuget Package AutoMapper
at ServerAPI
, HttpClient
, Newtonsoft.Json
at client side project, Mvc.Routing
and other dependency.
Using the Code
The source code has 2 parts: ServerAPI
project for WEB API, ClientSide
for client side call web API.
Host project ServerAPI
on the IIS/IIS express.
Access to the API through link: http://localhost/ConsumingAPI/api/Products to test the result.
Implement API server source code in ServerAPI
project, ProductsController.cs.
[HttpGet]
[Route("api/Products")]
public HttpResponseMessage GetProducts()
{
Mapper.CreateMap<Product, ProductDTO>();
var tempData = db.Products.ToList();
var products = Mapper.Map<List<Product>, List<ProductDTO>>(tempData);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);
return response;
}
From client side, call API and get data JSON/XML. After that, deserialize data to object ProductDTO
.
public static List<ProductDTO> GetListProduct()
{
List<ProductDTO> result;
const string url = "http://localhost/ConsumingAPI/api/Products ";
using (var client = new System.Net.Http.HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add
(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(url).Result;
var data = response.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<List<ProductDTO>>(data);
}
return result;
}
It is similar for POST
/PUT
/DELETE
methods. Kindly search and download any missing Nuget or dependency if building source code error.
public static void InsertProduct()
{
const string url = "http://localhost/ConsumingAPI/api/Products";
var product = new ProductDTO
{
ProductID = 0,
ProductName = "Test ProductName",
SupplierID = 1,
CategoryID = 1,
QuantityPerUnit = "10",
UnitPrice = 1000,
UnitsInStock = 6,
UnitsOnOrder = 10,
ReorderLevel = 1
};
using (var client = new System.Net.Http.HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add
(new MediaTypeWithQualityHeaderValue("application/json"));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(product);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync(url, content).Result;
}
}
Points of Interest
This code is very simple, you can change content type request to XML format.
History
This is the simple version, you can download the source code and improve it.