Reading the Body of a Request in .net

The purpose of this commodity is to sympathise and configure a HttpClient of our ain. If yous are very much interested in seeing the HTTP Protocol a little more than closely, then I hope this article will be gratifying. So, let's kickoff our talking.

Fine, nosotros will first clarify the basic idea of the HTTP protocol (not much, just the basics) and and so we will directly get to the HttpClient implementation part in the console awarding 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 spider web. Let's think almost the scenario when you lot have clicked on this article link to read it. A couple of operations has fired without your knowledge. What are the operations?

Yous have clicked on a link, your browser has formed a HTTP GET message with relevant information and fabricated a request to the c-sharocorner.com'south server. Now, the question is what does the request look? Ok, hither we will get one overview (that is a petty over-simplified simply very similar to the existent ane) of the GET request. The simplest example is hither.

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

Now, I take already said that this might not be the exact asking, considering in the exact asking in that location might be many header data to help the server for a better response.

Permit's sympathise the first line, the structure is like this:

[Method] [URL] [HTTP Version]

Method: Information technology defines the request type. Here the request blazon is GET. At that place are many others, like POST, PUT and DELETE.

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

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

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

Ok, we will not get much deepper into the HTTP protocol to concentrate on our actual topic. Let's first to configure our ain HTTP customer awarding that will consume services from the Web API. For that we need to create 2 different applications. I will be the server (Web API) and the panel application will be the HttpClient.

Create Web API to host RESTful service

In this awarding nosotros will implement a very unproblematic Web API that will host the HTTP service on the RESTful API. Take a look at the following code.

          using System;     using Organisation.Collections.Generic;     using System.Linq;     using System.Net;     using System.Cyberspace.Http;     using Arrangement.Spider web;     using TestWEB_API.Models;     using System.Spider web.SessionState;using System.Web.Http;     using System.Web.Mvc           namespace TestWEB_API.Controllers     {         public class ValuesController : ApiController         {                   public List<string> Go()             {                 List<cord> Li = new List<string>();                 Li.Add("Sourav");                 Li.Add("Ajay");                 Li.Add together("Manish");                 render Li;             }         }     }        

The Go() action is implemented very simply, we are just sending a collection of strings to the customer. That'due south all. Now we demand to concentrate on the client implementation function.

Implement HTTP client in Console application

Earlier proceeding, let's analyze some basic concepts. What is the archetype example of HTTP customer? Yeah, our browser. The browser knows very well how to form a HTTP request. Information technology does not thing which kind of request it is. It set header information (not one header, many are in that location, like fourth dimension-date, preferred data type) set host accost and proper HTTP protocol type and ship it to a destination, that happens behind the cenes. But in this case we will implement it from scratch (not from scratch exactly, because we will exist using the Httpclient class of the .Internet class library). Take a look at the following example.

          using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;     using Arrangement.Threading.Tasks;     using System.Net.Http;     using Organisation.Internet.Http.Headers;           namespace HttpClientAPP      {             class Programme           {             static void Principal(string[] args)             {                 HttpClient client = new HttpClient();                 client.BaseAddress = new Uri("http://localhost:11129/");                  // Add together an Have header for JSON format.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("awarding/json"));                  // List all Names.                 HttpResponseMessage response = client.GetAsync("api/Values").Event;  // 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 awarding. And 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

Thanks, we take created our first HTTP customer that has made a GET request to the Web API. That's fine and cool, now nosotros are interested in seeing the request and response message that we made at the time of the API telephone call and that we got in response. Hither is the sample implementation for that.

          using Arrangement;   using System.Collections.Generic;   using Organisation.Linq;   using System.Text;   using Organization.Threading.Tasks;   using System.Net.Http;   using Organization.Net.Http.Headers;       namespace HttpClientAPP   {          class Program        {           static void Main(cord[] 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("awarding/json"));                // List all Names.               HttpResponseMessage response = customer.GetAsync("api/Values").Result;  // Blocking telephone call!               if (response.IsSuccessStatusCode)               {                   Console.WriteLine("Request Message Information:- \n\northward" + response.RequestMessage + "\n");                   Console.WriteLine("Response Message Header \northward\northward" +  response.Content.Headers + "\n");               }               else               {                   Panel.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);               }               Console.ReadLine();           }       }   }        

The dark-green box shows the asking bulletin format that out HttpClient course has formed for the states. We are seeing that the asking type is Get and the HTTP protocol version is 1.1. In the header role but one header information is there. The asking is expecting JSON data in the torso of the response message.

The red box shows the response bulletin.

Http client response message

Post Request Method

In this article we will come across how to postal service data to the Web API using a .NET client. We know that the RESTful API tin can consume another service more than smoothly and whatsoever customer that understands HTTP tin consume the Spider web API. The .Net framework has provided squeamish classes to consume Web Services in any blazon of .Net awarding. In this commodity we will build a Panel application to consume a service from the Spider web API. So, let'south create the Web API part at kickoff. Have a expect at the following lawmaking.

          using System;      using Organisation.Collections.Generic;      using Organisation.Linq;       using System.Net;       using System.Internet.Http;       using Organization.Web.Http;               namespace WebAPI.Controllers       {           public course person           {               public cord name { go; gear up; }               public string surname { get; prepare; }           }              public class personController : ApiController           {               [HttpPost]               public void Post([FromBody] person p)               {                    }           }       }        

The person controller is simple to understand. We have kept only ane Post() method that nosotros busy with a [HttpPost] attribute. I believe the attribute decoration is non very helpful when our action name matches the HTTP verb. Anyhow the post method is taking one argument that nosotros will supply from the torso of the HTTP request and the argument type is the object type of the person class. So nosotros are sending a circuitous object from a .Internet client.

Let's see the .Net lawmaking now. You tin can find that we take replicated the aforementioned class that we defined in the Web API in the customer too. Then inside the Main() office we are creating one object of that class that we wll send to the Web API.

          using Arrangement;   using Organization.Collections.Generic;   using Organization.Linq;   using Organization.Text;   using Organisation.Threading.Tasks;   using ClassLibrary;   using System.Threading;   using System.Internet.Http;   using Organization.Net.Http.Headers;   using Organisation.Net.Http.Formatting;   using Newtonsoft.Json;      namespace ConsoleAPP   {       public course person       {           public cord name { get; set up; }           public cord surname { go; fix; }       }       form Program       {           static void Main(cord[] 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).Outcome;                   if (response.IsSuccessStatusCode)                   {                       Console.Write("Success");                   }                   else                       Console.Write("Error");               }           }       }   }        

We have specified the URL of the API and sent information to the Mail service action of the person controller using the "PostAsAsync" method. The consequence volition store a response variable and then nosotros 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-eight"?>      <packages>         <package id="EntityFramework" version="five.0.0" targetFramework="net45" />         <package id="Microsoft.AspNet.WebApi.Client" version="5.1.2" targetFramework="net45" />         <package id="Microsoft.AspNet.WebApi.Core" version="five.1.2" targetFramework="net45" />         <package id="Newtonsoft.Json" version="half-dozen.0.3" targetFramework="net45" />       </packages>        

Put and Delete Request Method

In this instance, we will telephone call Put() and Delete() actions of the Web API from a .Net client. I hope you are already familiar with the human relationship with HTTP verbs and the Spider web API.

Fine, so allow'due south meet implement the Put() method now. Nosotros know that Put() is able to update something in a RESTful service. Here is our Web API and nosotros will pass the complex type object as an argument to the Put() method.

          using Arrangement;      using System.Collections.Generic;       using Organisation.Linq;       using System.Internet;       using Arrangement.Cyberspace.Http;       using System.Web.Http;               namespace WebAPI.Controllers       {           public class person           {               public cord name { get; gear up; }               public string surname { get; set; }        }           public grade 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 Arrangement;       using System.Collections.Generic;       using Organisation.Linq;       using System.Text;       using System.Threading.Tasks;       using ClassLibrary;       using System.Threading;       using System.Cyberspace.Http;       using System.Cyberspace.Http.Headers;       using System.Internet.Http.Formatting;       using Newtonsoft.Json;               namespace ConsoleAPP       {           public course person           {               public string name { get; set; }               public string surname { get; prepare; }           }           class Program           {               static void Main(string[] args)               {                   using (var customer = new HttpClient())                   {                       person p = new person { name = "Sourav", surname = "Kayal" };                       customer.BaseAddress = new Uri("http://localhost:1565/");                       var response = client.PutAsJsonAsync("api/person", p).Result;                       if (response.IsSuccessStatusCode)                     {                           Panel.Write("Success");                       }                       else                           Console.Write("Fault");                   }               }           }       }        

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

Put action

The same is true for the Delete() functioning. Let's have a quick wait at the Delete() activity at present. 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 = customer.DeleteAsync("api/person/10").Result;         if (response.IsSuccessStatusCode)         {             Console.Write("Success");         }         else         Panel.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 past passing the value x as we are seeing in the following example.

Delete action

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

Determination

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

Reading the Body of a Request in .net

Source: https://www.c-sharpcorner.com/UploadFile/dacca2/http-request-methods-get-post-put-and-delete/

0 Response to "Reading the Body of a Request in .net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel