Call (Consume) Web API using HttpClient and Http WebRequest

 Print 
 Posted By :  ASPArticles
 Posted Date: Apr 08, 2018
 Category : 
 Post Hits : 161

In this tutorial, I am going to explain you how to create simple asp.net web api application and call using HttpClient and Http WebRequest separately in C#. We will be using Visual Studio 2013. We will cover below topics.
Calling Simple Method
Calling Method with Premitive Data Types using Get Request
Calling Method with Complex Data Types using Post Request

Creating Web API Empty Application

First step is to create ASP.NET Web API empty application as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net web api application

Now new window will open as shown below.
Now Select Empty Template, check on Web API checkbox and click on OK.

Selecting asp.net web api empty template

Now, a new project will be created as shown below.

Asp.net web api empty folder structure

Modify Web API Routing

Open WebApiConfig.cs file. Visual studio generates default routing as shown below. Add {action} in routeTemplate as highlighted in yellow.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApiDemo
{
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
}

Adding API Controller

Next step is to add api controller to application. Go to Controller folder → Add → Controller.. → select 'Web API 2 Controller-Empty'. Give its name HomeController and click on Add.
In home controller class, create a method Method1 which will return list of employee.

1) Method 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApiDemo.Controllers
{
public class HomeController : ApiController
{
    [HttpGet]
    public IEnumerable<string> Method1()
    {
        List<string> list = new List<string>();
        list.Add("Rahul");
        list.Add("Deepak");
        return list as IEnumerable<string>;  //list.AsEnumerable();
    }
}
}

Calling WebAPI using HttpClient in C# (Method1)

Make sure webapi application is running. Now, create a C# console application and call web api method using httpclient as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Net.Http.Headers;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        try
        {
            clsABC obj = new clsABC();
            string output = obj.GetDetailsUsinghttpClient().Result;
        }
        catch (Exception ex)
        {

        }
    }
}

public class clsABC
{
    public async Task<string > GetDetailsUsinghttpClient()
    {
        string Response = "";
        try
        {
            HttpResponseMessage HttpResponseMessage = null;
            using (var httpClient = new HttpClient())
            {
                // httpClient.BaseAddress = new Uri("http://localhost:32160/");
                httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage = await httpClient.GetAsync("http://localhost:32160//api/home/Method1");

                if (HttpResponseMessage.StatusCode == HttpStatusCode.OK)
                {
                    Response = HttpResponseMessage.Content.ReadAsStringAsync().Result;
                }
                else if (HttpResponseMessage.StatusCode == HttpStatusCode.BadRequest)
                {
                    Response = "Bad Request";
                }
                else if (HttpResponseMessage.StatusCode == HttpStatusCode.NotFound)
                {
                    Response = "Requested resource does not exists on server" ;
                }
                else
                {
                    Response = "Some error occured.";
                }
            }
        }
        catch (Exception ex)
        {

        }
        return Response;
    }
}
}
jSON OUTPUT:

Output can be seen below as json format.
["Rahul","Deepak"]

XML OUTPUT:

You can change response type from json to xml in accept parameter as shown below.
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Rahul</string>
  <string>Deepak</string>
</ArrayOfstring>

Calling WebAPI using Http WebRequest in C# (Method1)

Below is another way to call web api method using Http WebRequest as shown below.

class Program
{
    static void Main(string[] args)
    {
        clsABC obj = new clsABC();
        string output = obj.GetDetailsUsingHttpWebRequest();
    }
}

public class clsABC
{
    public string GetDetailsUsingHttpWebRequest()
    {
        string ResponseString = "";
        HttpWebResponse response = null;
        try
        {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost:32160/api/home/Method1");
            request.Accept = "application/json"; //"application/xml";
            response = ( HttpWebResponse)request.GetResponse();

            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    ResponseString = reader.ReadToEnd();
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                response = ( HttpWebResponse)ex.Response;
                ResponseString = "Some error occured: " + response.StatusCode.ToString();
            }
            else
            {
                ResponseString = "Some error occured: " + ex.Status.ToString();
            }
        }

        return ResponseString;
    }
}
jSON OUTPUT:

Output can be seen below as json format.
["Rahul","Deepak"]

XML OUTPUT:

You can change response type from json to xml in accept parameter as shown below.
request.Accept = "application/json";

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Rahul</string>
  <string>Deepak</string>
</ArrayOfstring>

2) Method2 (premitive data types)

Now add another method, Method2 in home controller as shown below. Method2 takes two integer through url and perform addition of two integers.

[HttpGet]
public string Method2(int FirstNumber, int SecondNumber)
{
return "Addition is: " + (FirstNumber + SecondNumber).ToString();
}

Calling Method2 using HttpClient

public async Task<string > GetDetailsUsinghttpClient()
{
    string Response = "";
    try
    {
        HttpResponseMessage HttpResponseMessage = null;
        using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); //application/xml
            HttpResponseMessage = await httpClient.GetAsync("http://localhost:32160/api/home/Method2?FirstNumber=10&SecondNumber=30");

            if (HttpResponseMessage.StatusCode == HttpStatusCode.OK)
            {
                Response = HttpResponseMessage.Content.ReadAsStringAsync().Result;
            }
            else
            {
                Response = "Some error occured." ;
            }
        }
    }
    catch (Exception ex)
    {
        Response = "Some error occured.";
    }
    return Response;
}
jSON OUTPUT:

"Addition is: 40"

XML OUTPUT:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
 Addition is: 40
</string>

Calling Method2 using Http WebRequest

public string GetDetailsUsingHttpWebRequest()
{
    string ResponseString = "";
    HttpWebResponse response = null;
    try
    {
        var request = (HttpWebRequest)WebRequest.Create("http://localhost:32160/api/home/Method2?FirstNumber=10&SecondNumber=30");
        request.Accept = "application/json" ; //"application/xml";
        response = (HttpWebResponse)request.GetResponse();

        using (var stream = response.GetResponseStream())
        {
            using (var reader = new StreamReader(stream))
            {
                ResponseString = reader.ReadToEnd();
            }
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            response = ( HttpWebResponse)ex.Response;
            ResponseString = "Some error occured: " + response.StatusCode.ToString();
        }
        else
        {
            ResponseString = "Some error occured: " + ex.Status.ToString();
        }
    }
    return ResponseString;
}

3) Method3 (Complex data types)

Now add another method, Method3 in home controller as shown below. Method3 takes complex object of two numbers using httpost attribute and perform addition of two numbers.

public class HomeController : ApiController
{
    [HttpPost]
    public string Method3(Calculator CalcObj)
    {
        return "Addition is: " + (CalcObj.FirstNumber + CalcObj.SecondNumber).ToString();
    }
}
public class Calculator
{
    public int FirstNumber { get; set; }
    public int SecondNumber { get; set; }
}

Calling Method3 using HttpClient

class Program
{
    static void Main(string[] args)
    {
        clsABC obj = new clsABC();
        string output = obj.GetDetailsUsinghttpClient().Result;
    }
}
public class Calculator
{
    public int SecondNumber { get; set; }
    public int FirstNumber { get; set; }
}
public class clsABC
{
    public async Task<string > GetDetailsUsinghttpClient()
    {
        string Response = "";
        try
        {
            HttpResponseMessage HttpResponseMessage = null;
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json"));
                //application/xml

                Calculator obj = new Calculator () { FirstNumber = 10, SecondNumber = 30 };

                JavaScriptSerializer jss = new JavaScriptSerializer();
                // serialize into json string
                var myContent = jss.Serialize(obj);

                var httpContent = new StringContent(myContent, Encoding.UTF8, "application/json");

                HttpResponseMessage = await httpClient.PostAsync("http://localhost:32160/api/home/Method3", httpContent);

                if (HttpResponseMessage.StatusCode == HttpStatusCode.OK)
                {
                    Response = HttpResponseMessage.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    Response = "Some error occured." ;
                }
            }
        }
        catch (Exception ex)
        {

        }
        return Response;
    }
}

Calling Method3 using Http WebRequest

class Program
{
    static void Main(string[] args)
    {
        clsABC obj = new clsABC();
        string output = obj.GetDetailsUsingHttpWebRequest();
    }
}
public class Calculator
{
    public int SecondNumber { get; set; }
    public int FirstNumber { get; set; }
}
public class clsABC
{
    public string GetDetailsUsingHttpWebRequest()
    {
        string ResponseString = "";
        HttpWebResponse response = null;
        try
        {
            var request = (HttpWebRequest)WebRequest.Create("http://localhost:32160/api/home/Method3");
            request.Accept = "application/json"; //"application/xml";
            request.Method = "POST";

            Calculator obj = new Calculator () { FirstNumber = 10, SecondNumber = 30 };
            JavaScriptSerializer jss = new JavaScriptSerializer();
            // serialize into json string
            var myContent = jss.Serialize(obj);

            var data = Encoding.ASCII.GetBytes(myContent);

            request.ContentType = "application/json";
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            response = ( HttpWebResponse)request.GetResponse();

            ResponseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                response = ( HttpWebResponse)ex.Response;
                ResponseString = "Some error occured: " + response.StatusCode.ToString();
            }
            else
            {
                ResponseString = "Some error occured: " + ex.Status.ToString();
            }
        }
        return ResponseString;
    }
}



blog comments powered by Disqus