Calling Web API Service from ASP.Net MVC Controller Action | ASP.Net MVC Tutorial | ASP.Net MVC Programmer Guide

Calling a Web API Service from an ASP.Net MVC Controller is very simple. We can achieve this scenario with the help of the object HttpClient,

Below C# code snippet gives you a good example on calling a Web API Service from an ASP.Net MVC Controller

  1. using System;   
  2.  using System.Collections.Generic;   
  3.  using System.Linq;   
  4.  using System.Text;   
  5.  using System.Threading.Tasks;   
  6.  using System.Net.Http;   
  7.  using System.Runtime.Serialization.Json;   
  8.  using Newtonsoft.Json;   
  9.    
  10.  namespace FRPI.WebApi.Helper   
  11.  {       
  12.      public class DeserializeData   
  13.      {   
  14.          readonly string webUrl = "http://IpaddressOrDomainName/RootFolder/api/Controller/";   
  15.          public List<OrderDetails> GetInvoiveNo(string invoiceno) {   
  16.              string uri = webUrl + invoiceno;   
  17.              using (HttpClient httpClient = new HttpClient()) {   
  18.                  Task<String> response = httpClient.GetStringAsync(uri);   
  19.                  return JsonConvert.DeserializeObjectAsync<List<OrderDetails>>(response.Result).Result;   
  20.              }   
  21.          }   
  22.      }   
  23.  }