Using the HttpRequestMessage
together with the HttpClient
you can easily send a HTTP Delete request in C#. Below we have a delete endpoint on https://localhost:7210/{id}
where we provide the id "123" as the resource we want to delete:
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Delete,
"https://localhost:7210/123");
var response = httpClient.Send(request);
In the above we make a new HttpClient
and a HttpRequestMessage
with the HttpMethod
Delete. We then use the basic Send()
method on the HttpClient
to send this. There is nothing more to it.
Having a JSON body for the delete request
You can also make a delete request that has a body. Note: this might not always be the best idea, see this page for more information. Having a body for the request is a little more cumbersome as you need to create the JSON you want to send, below is an example:
var httpClient = new HttpClient();
var deleteObject = new
{
Id = 123
};
var stringContent = new StringContent(
JsonConvert.SerializeObject(deleteObject), Encoding.UTF8,
"application/json");
var request = new HttpRequestMessage(HttpMethod.Delete,
"https://localhost:7210/");
request.Content = stringContent;
var response = httpClient.Send(request);
In the above we create a new HttpClient
and an anonymous object which will be the model for our request. We then use our anonymous object as input to a StringContent Object, the StringContent will be the body of the request and provide some headers such as the encoding (Encoding.UTF8
) and content-type (application/json
). As in the previous example we create a HttpRequestMessage
the difference here is that we also provide it with "Content", which is our StringContent
. In the end we call the Send()
method on the HttpClient
with our HttpRequestMessage
.
Making a Delete endpoint in ASP.NET
I have written a short blog post on how to make endpoints for the above here. It shows how you can make a DELETE endpoint in ASP.NET with or without a body.
That is it
I hope you enjoyed this post on how to send DELETE requests with the HttpClient in C#. Let me know in the comments down below what you think!