Jimmy James
Jimmy James

Reputation: 381

WebClient restful Delete

I have a simple Restful service being called from a console app so am using WebClient. I am wondering if this call for Delete is correct.

The url looks like localhost/RestService1/Person/1

using (var client = new WebClient()) 
{
    client.UploadString(url, "DELETE", "");
}

I don't like that UploadString does not have an overload without a data parameter. The passing of an empty parameter is not sitting well with me. Is there a better method to use for a DELETE?

I could use WebRequest but I want to just use WebClient to keep it consistent.

Here is the WebRequest block

var request = WebRequest.Create(url);
request.Method = "DELETE";
var response = (HttpWebResponse)request.GetResponse();

Both blocks work fine but what is best? Or is there a better way?

Upvotes: 34

Views: 29341

Answers (4)

Chevelle
Chevelle

Reputation: 248

Sorry this is my solution in vb.net i sure that anyone can translate to c#

It's very important to drop headers, i had to comment header about Accept and Content-Type and work fine..... of course I did send the token

Dim rest As WebClient = New WebClient()
rest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " & Token)
'rest.Headers.Add(HttpRequestHeader.Accept, "application/json")
'rest.Headers.Add(HttpRequestHeader.ContentType, "application/json")

result = System.Text.Encoding.UTF8.GetString(rest.UploadValues(host_api & uri, "DELETE", New NameValueCollection()))

Upvotes: 0

Simon
Simon

Reputation: 301

The following works for me:

client.UploadValues(url, "DELETE", new NameValueCollection()); 

Upvotes: 30

Darrel Miller
Darrel Miller

Reputation: 142014

Go get the Microsoft.Net.Http client libraries http://nuget.org/packages/Microsoft.Net.Http

HttpClient is a much better client to use for working with an API.

Upvotes: 3

RTigger
RTigger

Reputation: 1368

The WebClient class doesn't really lend well to restful api consumption, I've used 3rd party libraries like RestSharp in the past that are geared more towards this type of web request. I'm pretty sure RestSharp just uses HttpWebRequest under the covers, but it provides a lot of semantics that make consuming and reusing rest resources easier.

Upvotes: 3

Related Questions