How do I send a HTTP DELETE request with a body using C#'s HttpClient?
Posted: (EET/GMT+2)
By specification, a DELETE request may include a body, though many servers ignore it. The HttpClient class doesn't provide a built-in DeleteAsync overload that accepts content, but you can construct your own HttpRequestMessage.
To do this, and include for instance some JSON (aka string) content, you could write the HTTP call like this:
using (HttpClient client = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage()
{
Method = HttpMethod.Delete,
RequestUri = new Uri("https://api.example.com/items/123"),
Content = new StringContent("{ \"force\": true }",
Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
Console.WriteLine(response.StatusCode);
}
This pattern also works for custom methods or verbs. Always check your API documentation first; many REST endpoints expect DELETE requests without any body content, so use this approach only when the service explicitly supports it.