.NET Documentation

.NET 8.0

HttpClient.DeleteAsync Method

Asynchronously sends a DELETE request to the specified URI.

Overload List

Remarks

The DeleteAsync method sends an HTTP DELETE request to the specified Uniform Resource Identifier (URI) as an asynchronous operation. This is a common HTTP method used to request that a given resource be deleted on the server.

The operation will not block synchronously. The returned Task<HttpResponseMessage> will complete after the entire response (including content) is read.

The HttpResponseMessage returned by this method must be disposed of. It is recommended to use a using statement to ensure disposal.

Examples

Delete a resource using a string URI

using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public async Task DeleteResourceAsync(string resourceId)
    {
        using var httpClient = new HttpClient();
        string apiUrl = $"https://api.example.com/items/{resourceId}";

        try
        {
            using var response = await httpClient.DeleteAsync(apiUrl);

            // Check if the request was successful
            response.EnsureSuccessStatusCode();

            Console.WriteLine($"Resource with ID {resourceId} deleted successfully.");
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Error deleting resource: {ex.Message}");
        }
    }
}

Delete a resource using a Uri object and cancellation

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System;

public class Example
{
    public async Task DeleteResourceWithCancellationAsync(string resourceId, CancellationToken cancellationToken)
    {
        using var httpClient = new HttpClient();
        var requestUri = new Uri($"https://api.example.com/items/{resourceId}");

        try
        {
            using var response = await httpClient.DeleteAsync(requestUri, cancellationToken);

            response.EnsureSuccessStatusCode();

            Console.WriteLine($"Resource with ID {resourceId} deleted successfully.");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Delete operation was cancelled.");
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"Error deleting resource: {ex.Message}");
        }
    }
}

Parameters

Name Type Description
requestUri string? or Uri? The Uniform Resource Identifier (URI) to which the DELETE request is sent.
cancellationToken CancellationToken A cancellation token that can be used to cancel the request.

Return Value

Returns Task<HttpResponseMessage>. The task object represents the asynchronous operation. The Result property of the task object will contain an HttpResponseMessage indicating the result of the request.

Exceptions

Tip: For more complex scenarios involving custom headers or other HTTP configurations, consider using HttpClient.SendAsync with a constructed HttpRequestMessage.