Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Call (Consume) Web API using HttpClient and Http WebRequest

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 .

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

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

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;
usingSystem.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;
usingSystem.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespaceWebApiDemo.Controllers
{
public class HomeController : ApiController
{
    [HttpGet]
    public IEnumerablestring> Method1()
    {
        Liststring> list = new Liststring>();
        list.Add("Rahul");
        list.Add("Deepak");
        return list as IEnumerablestring>;  //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;
usingSystem.Collections.Generic;
using System.Linq;
using System.Text;
usingSystem.Threading.Tasks;
using System.Net.Http;
using System.Net;
using System.IO;
usingSystem.Net.Http.Headers;
usingSystem.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 Taskstring> GetDetailsUsinghttpClient()
    {
        string Response = "";
        try
        {
            HttpResponseMessageHttpResponseMessage = 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>Rahulstring>
  string>Deepakstring>
ArrayOfstring>


This post first appeared on ASPArticles, please read the originial post: here

Share the post

Call (Consume) Web API using HttpClient and Http WebRequest

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×