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

Blake Rivell picture Blake Rivell · Aug 16, 2016 · Viewed 18.2k times · Source

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;
}

Answer

Ben Anderson picture Ben Anderson · Oct 17, 2017

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);