Delete Request With Webclient C# Without Uploading Data

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 than closely, then I hope this article will be gratifying. So, allow's get-go our talking.

Fine, we will kickoff clarify the basic idea of the HTTP protocol (not much, just the nuts) and so nosotros volition direct go to the HttpClient implementation function in the console application and we will consume a Web API RESTful service on it.

HTTP is the protocol by which yous are reading this article, yous purchase your volume in Anazon.com, chat with your friend in Facebook (which I like the nigh) and exercise many more things in the web. Let's think virtually the scenario when you lot take clicked on this commodity 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 Become message with relevant information and made a request to the c-sharocorner.com'due south server. Now, the question is what does the request wait? Ok, here nosotros will go ane overview (that is a little over-simplified but very similar to the existent i) of the Go request. The simplest example is here.

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

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

Let'due south understand the start line, the structure is like this:

[Method] [URL] [HTTP Version]

Method: Information technology defines the request blazon. Here the request type is Become. There are many others, similar POST, PUT and DELETE.

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

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

Ok, we have learned the meaning of the commencement line. At present let's go to the second line. The second line is nada but one header information. The header name is Host. In the HTTP request and response there might exist 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 customer application that volition consume services from the Web API. For that we need to create two different applications. One will exist the server (Web API) and the console application will be the HttpClient.

Create Web API to host RESTful service

In this application nosotros volition implement a very unproblematic 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 Organisation.Internet;     using Arrangement.Cyberspace.Http;     using Arrangement.Spider web;     using TestWEB_API.Models;     using System.Spider web.SessionState;using Arrangement.Spider web.Http;     using Organization.Web.Mvc           namespace TestWEB_API.Controllers     {         public class ValuesController : ApiController         {                   public List<string> Get()             {                 Listing<cord> Li = new List<string>();                 Li.Add together("Sourav");                 Li.Add("Ajay");                 Li.Add("Manish");                 return Li;             }         }     }        

The Become() activeness is implemented very simply, we are merely sending a collection of strings to the customer. That'due south all. Now nosotros need to concentrate on the client implementation part.

Implement HTTP client in Console awarding

Before proceeding, allow's clarify some basic concepts. What is the classic case of HTTP client? Yes, our browser. The browser knows very well how to form a HTTP request. Information technology does non matter which kind of request it is. Information technology set header information (not ane header, many are there, like time-date, preferred information type) set host address and proper HTTP protocol type and send 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 be using the Httpclient grade of the .Net form library). Have a look at the post-obit example.

          using System;     using System.Collections.Generic;     using System.Linq;     using System.Text;     using Arrangement.Threading.Tasks;     using System.Internet.Http;     using Organization.Net.Http.Headers;           namespace HttpClientAPP      {             class Plan           {             static void Chief(cord[] args)             {                 HttpClient client = new HttpClient();                 client.BaseAddress = new Uri("http://localhost:11129/");                  // Add together 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                 {                     Panel.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);                 }             }         }     }        

Here we accept set a base accost that is nothing but the RESTful URL of our service awarding. Then we are requesting the server to return data in JSON format past 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 offset HTTP client that has made a Go asking to the Spider web API. That'due south fine and cool, now we are interested in seeing the asking and response bulletin 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 Organisation.Collections.Generic;   using Organisation.Linq;   using System.Text;   using System.Threading.Tasks;   using Organisation.Net.Http;   using System.Net.Http.Headers;       namespace HttpClientAPP   {          class Program        {           static void Master(cord[] args)           {               HttpClient client = new HttpClient();               client.BaseAddress = new Uri("http://localhost:11129/");                // Add an Accept header for JSON format.               client.DefaultRequestHeaders.Take.Add together(new MediaTypeWithQualityHeaderValue("application/json"));                // Listing all Names.               HttpResponseMessage response = customer.GetAsync("api/Values").Result;  // Blocking call!               if (response.IsSuccessStatusCode)               {                   Console.WriteLine("Asking Message Information:- \n\n" + response.RequestMessage + "\n");                   Console.WriteLine("Response Message Header \n\north" +  response.Content.Headers + "\n");               }               else               {                   Console.WriteLine("{0} ({i})", (int)response.StatusCode, response.ReasonPhrase);               }               Console.ReadLine();           }       }   }        

The dark-green box shows the asking message format that out HttpClient class has formed for us. We are seeing that the asking type is GET and the HTTP protocol version is ane.one. In the header part but i header information is at that place. The request is expecting JSON data in the trunk of the response message.

The red box shows the response message.

Http client response message

Post Request Method

In this article we will run into how to post data to the Web API using a .Net customer. We know that the RESTful API can consume some other service more smoothly and whatsoever customer that understands HTTP can consume the Web API. The .NET framework has provided overnice classes to consume Spider web Services in whatsoever blazon of .NET application. In this article nosotros volition build a Console application to consume a service from the Web API. And so, allow's create the Web API office at commencement. Accept a await at the post-obit code.

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

The person controller is simple to understand. We take kept only one Post() method that nosotros decorated with a [HttpPost] attribute. I believe the attribute decoration is non very helpful when our activity name matches the HTTP verb. Anyway the postal service method is taking one argument that nosotros volition supply from the trunk of the HTTP asking and the argument blazon is the object type of the person form. And then we are sending a circuitous object from a .NET client.

Permit's see the .NET code now. You can find that nosotros accept replicated the aforementioned class that nosotros divers in the Web API in the client too. Then within the Main() function we are creating one object of that grade that we wll transport to the Web API.

          using System;   using Organisation.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;   using ClassLibrary;   using Organization.Threading;   using System.Net.Http;   using System.Internet.Http.Headers;   using Arrangement.Net.Http.Formatting;   using Newtonsoft.Json;      namespace ConsoleAPP   {       public class person       {           public string name { get; set; }           public string surname { get; set; }       }       form Program       {           static void Master(string[] args)           {               using (var client = new HttpClient())               {                   person p = new person { proper noun = "Sourav", surname = "Kayal" };                   customer.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 event will shop a response variable and then we bank check the "IsSuccessStatuscode" of the object.

At present, 1 thing to exist considered during the client application development. It's practiced to install the following packages in the application.

          <?xml version="1.0" encoding="utf-eight"?>      <packages>         <package id="EntityFramework" version="5.0.0" targetFramework="net45" />         <package id="Microsoft.AspNet.WebApi.Customer" version="5.i.2" targetFramework="net45" />         <package id="Microsoft.AspNet.WebApi.Core" version="v.one.2" targetFramework="net45" />         <packet id="Newtonsoft.Json" version="half dozen.0.3" targetFramework="net45" />       </packages>        

Put and Delete Asking Method

In this example, nosotros volition call Put() and Delete() actions of the Web API from a .NET client. I hope y'all are already familiar with the relationship with HTTP verbs and the Spider 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 Spider web API and we will laissez passer the complex blazon object as an argument to the Put() method.

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

Ok, at present we will implement a client application that volition practice a Put() performance to the Web API. Have a await at the post-obit code.

          using Organization;       using System.Collections.Generic;       using Arrangement.Linq;       using System.Text;       using System.Threading.Tasks;       using ClassLibrary;       using Organisation.Threading;       using Organization.Net.Http;       using System.Net.Http.Headers;       using Organization.Net.Http.Formatting;       using Newtonsoft.Json;               namespace ConsoleAPP       {           public class person           {               public cord name { become; ready; }               public string surname { become; 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 aforementioned object blazon to the Web API that it is expecting a Put() action/method. In one case 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() operation. Let'southward take a quick look at the Delete() activity 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 = customer.DeleteAsync("api/person/ten").Result;         if (response.IsSuccessStatusCode)         {             Console.Write("Success");         }         else         Console.Write("Fault");     }        

And the Delete() action in the API.

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

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

Delete action

Cool, and then 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 ain using the HttpClient class of the .Net library. Since the client is getting the response asynchronously, we need to use .Net 4.5 to back up Asynchronous operations.

cornwallcoulte1989.blogspot.com

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

0 Response to "Delete Request With Webclient C# Without Uploading Data"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel