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.

  1.  using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web;  
  7. using TestWEB_API.Models;  
  8. using System.Web.SessionState;using System.Web.Http;  
  9. using System.Web.Mvc  
  10.    
  11. namespace TestWEB_API.Controllers  
  12. {  
  13.     public class ValuesController : ApiController  
  14.     {        
  15.         public List<string> Get()  
  16.         {  
  17.             List<string> Li = new List<string>();  
  18.             Li.Add("Sourav");  
  19.             Li.Add("Ajay");  
  20.             Li.Add("Manish");  
  21.             return Li;  
  22.         }  
  23.     }  

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.

  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.Net.Http.Headers;   
  8.   
  9. namespace HttpClientAPP  
  10. {     
  11.     class Program   
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             HttpClient client = new HttpClient();  
  16.             client.BaseAddress = new Uri("http://localhost:11129/");   
  17.             // Add an Accept header for JSON format.  
  18.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));   
  19.             // List all Names.  
  20.             HttpResponseMessage response = client.GetAsync("api/Values").Result;  // Blocking call!  
  21.             if (response.IsSuccessStatusCode)  
  22.             {  
  23.                 var products = response.Content.ReadAsStringAsync().Result;   
  24.             }  
  25.             else  
  26.             {  
  27.                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);  
  28.             }  
  29.         }  
  30.     }  

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.

  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.Net.Http.Headers;   
  8.   
  9. namespace HttpClientAPP  
  10. {     
  11.     class Program   
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             HttpClient client = new HttpClient();  
  16.             client.BaseAddress = new Uri("http://localhost:11129/");   
  17.             // Add an Accept header for JSON format.  
  18.             client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));   
  19.             // List all Names.  
  20.             HttpResponseMessage response = client.GetAsync("api/Values").Result;  // Blocking call!  
  21.             if (response.IsSuccessStatusCode)  
  22.             {  
  23.                 Console.WriteLine("Request Message Information:- \n\n" + response.RequestMessage + "\n");  
  24.                 Console.WriteLine("Response Message Header \n\n" +  response.Content.Headers + "\n");  
  25.             }  
  26.             else  
  27.             {  
  28.                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);  
  29.             }  
  30.             Console.ReadLine();  
  31.         }  
  32.     }  

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Net.Http;   
  6. using System.Web.Http;      
  7.   
  8. namespace WebAPI.Controllers   
  9. {   
  10.     public class person   
  11.     {   
  12.         public string name { getset; }   
  13.         public string surname { getset; }   
  14.     }      
  15.     public class personController : ApiController   
  16.     {   
  17.         [HttpPost]   
  18.         public void Post([FromBody] person p)   
  19.         {        
  20.         }   
  21.     }   

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.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ClassLibrary;  
  7. using System.Threading;  
  8. using System.Net.Http;  
  9. using System.Net.Http.Headers;  
  10. using System.Net.Http.Formatting;  
  11. using Newtonsoft.Json;  
  12.   
  13. namespace ConsoleAPP  
  14. {  
  15.     public class person  
  16.     {  
  17.         public string name { getset; }  
  18.         public string surname { getset; }  
  19.     }  
  20.     class Program  
  21.     {  
  22.         static void Main(string[] args)  
  23.         {  
  24.             using (var client = new HttpClient())  
  25.             {  
  26.                 person p = new person { name = "Sourav", surname = "Kayal" };  
  27.                 client.BaseAddress = new Uri("http://localhost:1565/");  
  28.                 var response = client.PostAsJsonAsync("api/person", p).Result;  
  29.                 if (response.IsSuccessStatusCode)  
  30.                 {  
  31.                     Console.Write("Success");  
  32.                 }  
  33.                 else  
  34.                     Console.Write("Error");  
  35.             }  
  36.         }  
  37.     }  

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.

  1.  <?xml version="1.0" encoding="utf-8"?>  
  2. <packages>   
  3.   <package id="EntityFramework" version="5.0.0" targetFramework="net45" />   
  4.   <package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />   
  5.   <package id="Microsoft.AspNet.WebApi.Core" version="5.1.2" targetFramework="net45" />   
  6.   <package id="Newtonsoft.Json" version="6.0.3" targetFramework="net45" />   
  7. </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.

  1. using System;  
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Net.Http;   
  6. using System.Web.Http;      
  7.   
  8. namespace WebAPI.Controllers   
  9. {   
  10.     public class person   
  11.     {   
  12.         public string name { getset; }   
  13.         public string surname { getset; }        }   
  14.     public class personController : ApiController   
  15.     {   
  16.         [HttpPut]   
  17.         public void Put([FromBody] person p)   
  18.         {   
  19.         }   
  20.     }   
  21. }   

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.

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.Threading.Tasks;   
  6. using ClassLibrary;   
  7. using System.Threading;   
  8. using System.Net.Http;   
  9. using System.Net.Http.Headers;   
  10. using System.Net.Http.Formatting;   
  11. using Newtonsoft.Json;      
  12.   
  13. namespace ConsoleAPP   
  14. {   
  15.     public class person   
  16.     {   
  17.         public string name { getset; }   
  18.         public string surname { getset; }   
  19.     }   
  20.     class Program   
  21.     {   
  22.         static void Main(string[] args)   
  23.         {   
  24.             using (var client = new HttpClient())   
  25.             {   
  26.                 person p = new person { name = "Sourav", surname = "Kayal" };   
  27.                 client.BaseAddress = new Uri("http://localhost:1565/");   
  28.                 var response = client.PutAsJsonAsync("api/person", p).Result;   
  29.                 if (response.IsSuccessStatusCode)  
  30.                 {   
  31.                     Console.Write("Success");   
  32.                 }   
  33.                 else   
  34.                     Console.Write("Error");   
  35.             }   
  36.         }   
  37.     }   
  38. }   

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.
  1.  using (var client = new HttpClient())    
  2. {    
  3.     client.BaseAddress = new Uri("http://localhost:1565/");    
  4.     var response = client.DeleteAsync("api/person/10").Result;    
  5.     if (response.IsSuccessStatusCode)    
  6.     {    
  7.         Console.Write("Success");    
  8.     }    
  9.     else    
  10.     Console.Write("Error");    

And the Delete() action in the API.   

  1.  [HttpDelete]    
  2. public void Delete([FromUri] Int32 Id)    
  3. {    
  4. }    

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.

Up Next
    Ebook Download
    View all
    Learn
    View all