HTTP Operations GET, POST, PUT and DELETE From .NET Client

The purpose of this article is to understand and configure a HttpClient of our own. If you are very much interested in seeing the HTTP Protocol a little more closely, then I hope this article will be gratifying. So, let's start our talking.

Fine, we will first clarify the basic idea of the HTTP protocol (not much, just the basics) and then we will directly go to the HttpClient implementation part in the console application and we will consume a Web API RESTful service on it.

HTTP is the protocol by which you are reading this article, you buy your book in Anazon.com, chat with your friend in Facebook (which I like the most) and do many more things in the web. Let's think about the scenario when you have clicked on this article link to read it. A couple of operations has fired without your knowledge. What are the operations?

You have clicked on a link, your browser has formed a HTTP GET message with relevant information and made a request to the c-sharocorner.com's server. Now, the question is what does the request look? Ok, here we will get one overview (that is a little over-simplified but very similar to the real one) of the GET request. The simplest example is here.

GET: http://c-sharpcorner.com/Articles/myarticle.aspx HTTP/1.1
Host: c-sharpcorner.com

Now, I have already said that this might not be the exact request, because in the exact request there might be many header information to help the server for a better response.

Let's understand the first line, the structure is like this:

[Method] [URL] [HTTP Version]

Method: It defines the request type. Here the request type is GET. There are many others, like POST, PUT and DELETE.

URL: The URL defines the specific URL that we want to get from the server. Obviously this URL is an arbitrary one and provided for our understanding.

HTTP Version: The HTTP version defines the current HTTP version of this request. We are seeing that the HTTP version is 1.1 which is the latest one after 1.0 and dominating the WWW since 1999.

Ok, we have learned the meaning of the first line. Now let's go to the second line. The second line is nothing but one header information. The header name is Host. In the HTTP request and response there might be n number of headers. Other than the “Host” header, all are optional. The host header contains the server name.

Ok, we will not go much deepper into the HTTP protocol to concentrate on our actual topic. Let's start to configure our own HTTP client application that will consume services from the Web API. For that we need to create two different applications. One will be the server (Web API) and the console application will be the HttpClient.

Create Web API to host RESTful service

In this application we will implement a very simple Web API that will host the HTTP service on the RESTful API. Have a look at the following code.

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Net;    
using System.Net.Http;    
using System.Web;    
using TestWEB_API.Models;    
using System.Web.SessionState;using System.Web.Http;    
using System.Web.Mvc    
     
namespace TestWEB_API.Controllers    
{    
    public class ValuesController : ApiController    
    {          
        public List<string> Get()    
        {    
            List<string> Li = new List<string>();    
            Li.Add("Sourav");    
            Li.Add("Ajay");    
            Li.Add("Manish");    
            return Li;    
        }    
    }    
}

The Get() action is implemented very simply, we are just sending a collection of strings to the client. That's all. Now we need to concentrate on the client implementation part.

Implement HTTP client in Console application

Before proceeding, let's clarify some basic concepts. What is the classic example of HTTP client? Yes, our browser. The browser knows very well how to form a HTTP request. It does not matter which kind of request it is. It set header information (not one header, many are there, like time-date, preferred data type) set host address and proper HTTP protocol type and send it to a destination, that happens behind the cenes. But in this example we will implement it from scratch (not from scratch exactly, because we will be using the Httpclient class of the .NET class library). Have a look at the following example.

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Threading.Tasks;    
using System.Net.Http;    
using System.Net.Http.Headers;     
    
namespace HttpClientAPP     
{        
    class Program      
    {    
        static void Main(string[] args)    
        {    
            HttpClient client = new HttpClient();    
            client.BaseAddress = new Uri("http://localhost:11129/");     
            // Add an Accept header for JSON format.    
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));     
            // List all Names.    
            HttpResponseMessage response = client.GetAsync("api/Values").Result;  // Blocking call!    
            if (response.IsSuccessStatusCode)    
            {    
                var products = response.Content.ReadAsStringAsync().Result;     
            }    
            else    
            {    
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);    
            }    
        }    
    }    
}

Here we have set a base address that is nothing but the RESTful URL of our service application. Then we are requesting the server to return data in JSON format by setting the expected content type header. Then we are reading the response information asynchronously.

In the output we are getting data in JSON format, which is what is expected.

Http client in Console application

Cheers, we have created our first HTTP client that has made a GET request to the Web API. That's fine and cool, now we are interested in seeing the request and response message that we made at the time of the API call and that we got in response. Here is the sample implementation for that.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Net.Http;  
using System.Net.Http.Headers;   
  
namespace HttpClientAPP  
{     
    class Program   
    {  
        static void Main(string[] args)  
        {  
            HttpClient client = new HttpClient();  
            client.BaseAddress = new Uri("http://localhost:11129/");   
            // Add an Accept header for JSON format.  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));   
            // List all Names.  
            HttpResponseMessage response = client.GetAsync("api/Values").Result;  // Blocking call!  
            if (response.IsSuccessStatusCode)  
            {  
                Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");  
                Console.WriteLine("Response Message Header \n\n" +  response.Content.Headers + "\n");  
            }  
            else  
            {  
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);  
            }  
            Console.ReadLine();  
        }  
    }  
}

The green box shows the request message format that out HttpClient class has formed for us. We are seeing that the request type is GET and the HTTP protocol version is 1.1. In the header part only one header information is there. The request is expecting JSON data in the body of the response message.

The red box shows the response message.

Http client response message

Post Request Method

In this article we will see how to post data to the Web API using a .NET client. We know that the RESTful API can consume another service more smoothly and any client that understands HTTP can consume the Web API. The .NET framework has provided nice classes to consume Web Services in any type of .NET application. In this article we will build a Console application to consume a service from the Web API. So, let's create the Web API part at first. Have a look at the following code.

using System;     
using System.Collections.Generic;     
using System.Linq;      
using System.Net;      
using System.Net.Http;      
using System.Web.Http;         
    
namespace WebAPI.Controllers      
{      
    public class person      
    {      
        public string name { get; set; }      
        public string surname { get; set; }      
    }         
    public class personController : ApiController      
    {      
        [HttpPost]      
        public void Post([FromBody] person p)      
        {           
        }      
    }      
}

The person controller is simple to understand. We have kept only one Post() method that we decorated with a [HttpPost] attribute. I believe the attribute decoration is not very helpful when our action name matches the HTTP verb. Anyway the post method is taking one argument that we will supply from the body of the HTTP request and the argument type is the object type of the person class. So we are sending a complex object from a .NET client.

Let's see the .NET code now. You can find that we have replicated the same class that we defined in the Web API in the client too. Then within the Main() function we are creating one object of that class that we wll send to the Web API.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using ClassLibrary;  
using System.Threading;  
using System.Net.Http;  
using System.Net.Http.Headers;  
using System.Net.Http.Formatting;  
using Newtonsoft.Json;  
  
namespace ConsoleAPP  
{  
    public class person  
    {  
        public string name { get; set; }  
        public string surname { get; set; }  
    }  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            using (var client = new HttpClient())  
            {  
                person p = new person { name = "Sourav", surname = "Kayal" };  
                client.BaseAddress = new Uri("http://localhost:1565/");  
                var response = client.PostAsJsonAsync("api/person", p).Result;  
                if (response.IsSuccessStatusCode)  
                {  
                    Console.Write("Success");  
                }  
                else  
                    Console.Write("Error");  
            }  
        }  
    }  
} 

We have specified the URL of the API and sent data to the Post action of the person controller using the “PostAsAsync” method. The result will store a response variable and then we check the "IsSuccessStatuscode" of the object.

Now, one thing to be considered during the client application development. It's good to install the following packages in the application.

<?xml version="1.0" encoding="utf-8"?>     
<packages>      
  <package id="EntityFramework" version="5.0.0" targetFramework="net45" />      
  <package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />      
  <package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />      
  <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />      
</packages> 

Put and Delete Request Method

In this example, we will call Put() and Delete() actions of the Web API from a .NET client. I hope you are already familiar with the relationship with HTTP verbs and the Web API.

Fine, so let's see implement the Put() method now. We know that Put() is able to update something in a RESTful service. Here is our Web API and we will pass the complex type object as an argument to the Put() method.

using System;     
using System.Collections.Generic;      
using System.Linq;      
using System.Net;      
using System.Net.Http;      
using System.Web.Http;         
    
namespace WebAPI.Controllers      
{      
    public class person      
    {      
        public string name { get; set; }      
        public string surname { get; set; }        }      
    public class personController : ApiController      
    {      
        [HttpPut]      
        public void Put([FromBody] person p)      
        {      
        }      
    }      
}

Ok, now we will implement a client application that will do a Put() operation to the Web API. Have a look at the following code.

using System;      
using System.Collections.Generic;      
using System.Linq;      
using System.Text;      
using System.Threading.Tasks;      
using ClassLibrary;      
using System.Threading;      
using System.Net.Http;      
using System.Net.Http.Headers;      
using System.Net.Http.Formatting;      
using Newtonsoft.Json;         
    
namespace ConsoleAPP      
{      
    public class person      
    {      
        public string name { get; set; }      
        public string surname { get; set; }      
    }      
    class Program      
    {      
        static void Main(string[] args)      
        {      
            using (var client = new HttpClient())      
            {      
                person p = new person { name = "Sourav", surname = "Kayal" };      
                client.BaseAddress = new Uri("http://localhost:1565/");      
                var response = client.PutAsJsonAsync("api/person", p).Result;      
                if (response.IsSuccessStatusCode)    
                {      
                    Console.Write("Success");      
                }      
                else      
                    Console.Write("Error");      
            }      
        }      
    }      
} 

We are sending the same object type to the Web API that it is expecting a Put() action/method. Once we run the application we will see that the data has been obtained using the Put() action.

Put action

The same is true for the Delete() operation. Let's have a quick look at the Delete() action now. Here is the client code. In the case of Delete() we are sending the key value that is an Integer type.

using (var client = new HttpClient())    
{    
    client.BaseAddress = new Uri("http://localhost:1565/");    
    var response = client.DeleteAsync("api/person/10").Result;    
    if (response.IsSuccessStatusCode)    
    {    
        Console.Write("Success");    
    }    
    else    
    Console.Write("Error");    
}

And the Delete() action in the API.

[HttpDelete]    
public void Delete([FromUri] Int32 Id)    
{    
}

If everything is fine then it will call the Delete() action by passing the value 10 as we are seeing in the following example.

Delete action

Cool, so we have seen how to call the Put() and Delete() actions of the Web API from a .NET client.

Conclusion

In this article, we have learned how to make a HTTP client of our own using the HttpClient class of the .NET library. Since the client is getting the response asynchronously, we need to use .NET 4.5 to support Asynchronous operations.


Similar Articles