In this article I will explain with an example, how to read response from Web API using HttpClient in C#.
The Web API 2 Controller method will fetch records from database using Entity Framework in ASP.Net MVC.
The Web API 2 Controller method will be called using HttpClient class along with parameters in Console Application using C#.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Read response from Web API using HttpClient in C#
 
 
Model
The CustomerModel class consists of the following property.
 
public class CustomerModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { get; set; }
}
 
 
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Read response from Web API using HttpClient in C#
 
Then give it a suitable name and click OK.
Read response from Web API using HttpClient in C#
 
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
 
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}
 
The next step is to code the Web API Controller. The Web API Controller consists of a method named GetCustomers which accepts an object of CustomerModel.
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.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
public class CustomerAPIController : ApiController
{
    [Route("api/CustomerAPI/GetCustomers")]
    [HttpPost]
    public List<Customer> GetCustomers(CustomerModel customer)
    {
        NorthwindEntities entities = new NorthwindEntities();
        return (from c in entities.Customers.Take(10)
                where c.ContactName.StartsWith(customer.Name) || string.IsNullOrEmpty(customer.Name)
                select c).ToList();
    }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.Text;
using System.Net.Http;
using System.Web.Script.Serialization;
 
Note: In order to use the System.Web.Script.Serialization namespace, you will need to add reference of System.Web.Extensions assembly to your project, for more details refer here.
 
 
Calling the Web API using HttpClient class in Console Application
Inside the Main method, the captured value of Name is wrapped into a JSON object which is then serialized into a JSON string. 
The URL of the Web API along with its Controller method and the serialized JSON string is passed to the PostAsync method of the HttpClient class.
The PostAsync 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 Customer class objects.
Finally, the names of all matching Customers are displayed as Output in the Console Application.
static void Main(string[] args)
{
    Start:
    Console.Write("Enter Name: ");
    string name = Console.ReadLine();
    string apiUrl = "http://localhost:26404/api/CustomerAPI";
    var input = new
    {
        Name = name,
    };
    string inputJson = (new JavaScriptSerializer()).Serialize(input);
 
    HttpClient client = new HttpClient();
    HttpContent inputContent = newStringContent(inputJson, Encoding.UTF8, "application/json");
    HttpResponseMessage response = client.PostAsync(apiUrl + "/GetCustomers", inputContent).Result;
    if (response.IsSuccessStatusCode)
    {
        List<Customer> customers = (new JavaScriptSerializer()).Deserialize<List<Customer>>(response.Content.ReadAsStringAsync().Result);
        if (customers.Count > 0)
        {
            foreach (Customer customer in customers)
            {
                Console.WriteLine(customer.ContactName);
            }
        }
        else
        {
            Console.WriteLine("No records found.");
        }
    }
                      
    Console.WriteLine();
    goto Start;
}
 
public classCustomer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
}
 
 
Screenshot
Read response from Web API using HttpClient in C#
 
 
Downloads