Click here to Skip to main content
15,881,812 members
Articles / Web Development / ASP.NET
Tip/Trick

Simple Client Side Consume ASP.NET Web API Server

Rate me:
Please Sign up or sign in to vote.
4.38/5 (7 votes)
12 May 2017CPOL1 min read 32.2K   11   9
Send HTTP GET requests, consume ASP.NET Web API server

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.

Image 1

Host project ServerAPI on the IIS/IIS express.

Access to the API through link: http://localhost/ConsumingAPI/api/Products to test the result.

Image 2

Implement API server source code in ServerAPI project, ProductsController.cs.

C#
// GET api/Products
       [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.

JavaScript
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.

JavaScript
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect OSM Solution Vietnam Ltd. Co.
Vietnam Vietnam
We are working in Web Application with SPA, MVC domain. Beside we are master in Management Information Systems, how to use IS to improve decision making and knowledge sharing in open learning organization.

Comments and Discussions

 
QuestionNot enought detail in the text Pin
kannankeril30-Aug-15 13:46
kannankeril30-Aug-15 13:46 
AnswerRe: Not enought detail in the text Pin
Chinh Vo Wili30-Aug-15 17:23
professionalChinh Vo Wili30-Aug-15 17:23 
QuestionNice Article Pin
Santhakumar Munuswamy @ Chennai29-Aug-15 19:36
professionalSanthakumar Munuswamy @ Chennai29-Aug-15 19:36 
GeneralMy vote of 3 Pin
Member 1194253528-Aug-15 1:28
Member 1194253528-Aug-15 1:28 
GeneralRe: My vote of 3 Pin
Chinh Vo Wili28-Aug-15 2:46
professionalChinh Vo Wili28-Aug-15 2:46 
AnswerFormat issues.. Pin
Afzaal Ahmad Zeeshan27-Aug-15 2:04
professionalAfzaal Ahmad Zeeshan27-Aug-15 2:04 
GeneralRe: Format issues.. Pin
Chinh Vo Wili27-Aug-15 3:45
professionalChinh Vo Wili27-Aug-15 3:45 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Aug-15 1:22
Humayun Kabir Mamun27-Aug-15 1:22 
GeneralRe: My vote of 5 Pin
Chinh Vo Wili27-Aug-15 3:29
professionalChinh Vo Wili27-Aug-15 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.