Passing body content when calling a Delete Web API method using System.Net.Http
Asked Answered
H

3

18

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;
}
Herriott answered 16/8, 2016 at 13:27 Comment(1)
You could try creating a HttpRequestMessage manually with DELETE method and the the HttpContent then use the HttpClient.SendAsyncRejoice
L
39

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);
Laddie answered 16/10, 2017 at 23:41 Comment(1)
For anyone using System.Text.Json: Instead of JsonConvert.SerializeObject(object), use JsonSerializer.Serialize(object)Archduchy
A
4

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.

Atchley answered 16/8, 2016 at 14:8 Comment(0)
F
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
            {

            }
Fluorine answered 6/7, 2018 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.