21

I have a scenario where I need to call my Web API Delete method constructed like the following:

// DELETE: api/products/{id}/headers
[HttpDelete("{id}/headers")]
public void DeleteProductHeaders(int id, [FromBody] string query)
{
}

The trick is that in order to get the query over I need to send it through the body and DeleteAsync does not have a param for json like post does. Does anyone know how I can do this using System.Net.Http client in c#?

// Delete a product's headers
public void DeleteProductHeaders(int id, string query)
{
    using (var client = GetClient())
    {
        HttpResponseMessage response;
        try
        {
            // HTTP DELETE
            response = client.DeleteAsync($"api/products/{id}/headers").Result;
        }
        catch (Exception ex)
        {
            throw new Exception("Unable to connect to the server", ex);
        }
    }
    return retVal;
}
1
  • 2
    You could try creating a HttpRequestMessage manually with DELETE method and the the HttpContent then use the HttpClient.SendAsync Commented Aug 16, 2016 at 13:38

3 Answers 3

43

Here is how I accomplished it

var request = new HttpRequestMessage(HttpMethod.Delete, "http://www.example.com/");
request.Content = new StringContent(JsonConvert.SerializeObject(object), Encoding.UTF8, "application/json");
await this.client.SendAsync(request);
Sign up to request clarification or add additional context in comments.

1 Comment

For anyone using System.Text.Json: Instead of JsonConvert.SerializeObject(object), use JsonSerializer.Serialize(object)
5

The reason HttpClient is designed this way is rooted in the HTTP 1.1 specification. While the spec technically permits message bodies on DELETE requests, it's an unconventional practice, and the specification doesn't provide clear semantics for it as it's defined here. HttpClient strictly adheres to the HTTP specification, which means it doesn't support adding a message body to DELETE requests.

As a result, you may find limitations when attempting to include a message body in DELETE requests, which can be demonstrated through practical scenarios. If you encounter this limitation and need to send data typically placed in the message body, you might consider alternative approaches like using HttpRequestMessage described here.

In my personal perspective, I believe DELETE should allow for message bodies and not be disregarded by servers, as there are indeed use cases, such as the one you've mentioned here.

For a more comprehensive discussion of this topic, please refer to this resource.

Edit: Simply use VsCode's ThunderClient Extension or Postman (instead of Visual Studios app.http files) for calling DELETE api's with a Body.

Comments

2

My API as below:

// DELETE api/values
public void Delete([FromBody]string value)
{
}

Calling from C# server side

            string URL = "http://localhost:xxxxx/api/values";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "DELETE";
            request.ContentType = "application/json";
            string data = Newtonsoft.Json.JsonConvert.SerializeObject("your body parameter value");
            request.ContentLength = data.Length;
            StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
            requestWriter.Write(data);
            requestWriter.Close();

            try
            {
                WebResponse webResponse = request.GetResponse();
                Stream webStream = webResponse.GetResponseStream();
                StreamReader responseReader = new StreamReader(webStream);
                string response = responseReader.ReadToEnd();

                responseReader.Close();
            }
            catch
            {

            }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.