29

I am trying to create a Patch request with theHttpClient in dotnet core. I have found the other methods,

using (var client = new HttpClient())
{
    client.GetAsync("/posts");
    client.PostAsync("/posts", ...);
    client.PutAsync("/posts", ...);
    client.DeleteAsync("/posts");
}

but can't seem to find the Patch option. Is it possible to do a Patch request with the HttpClient? If so, can someone show me an example how to do it?

Lukas
  • 1,699
  • 1
  • 16
  • 49
Tom Aalbers
  • 4,574
  • 5
  • 29
  • 51

3 Answers3

31

Thanks to Daniel A. White's comment, I got the following working.

using (var client = new HttpClient())
{       
    var request = new HttpRequestMessage(new HttpMethod("PATCH"), "your-api-endpoint");

    try
    {
        response = await client.SendAsync(request);
    }
    catch (HttpRequestException ex)
    {
        // Failed
    }
}

EDIT: For .NET (Core) see @LxL answer.

KoalaBear
  • 2,755
  • 2
  • 25
  • 29
Tom Aalbers
  • 4,574
  • 5
  • 29
  • 51
12

HttpClient does not have patch out of the box. Simply do something like this:

// more things here
using (var client = new HttpClient())
{
    client.BaseAddress = hostUri;
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Credentials);
    var method = "PATCH";
    var httpVerb = new HttpMethod(method);
    var httpRequestMessage =
        new HttpRequestMessage(httpVerb, path)
        {
            Content = stringContent
        };
    try
    {
        var response = await client.SendAsync(httpRequestMessage);
        if (!response.IsSuccessStatusCode)
        {
            var responseCode = response.StatusCode;
            var responseJson = await response.Content.ReadAsStringAsync();
            throw new MyCustomException($"Unexpected http response {responseCode}: {responseJson}");
        }
    }
    catch (Exception exception)
    {
        throw new MyCustomException($"Error patching {stringContent} in {path}", exception);
    }
}
diegosasw
  • 13,734
  • 16
  • 95
  • 159
7

As of Feb 2022 Update 2022

###Original Answer###

As of .Net Core 2.1, the PatchAsync() is now available for HttpClient

Snapshot for applies to

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync

LxL
  • 1,878
  • 2
  • 20
  • 39