Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a patch request using HttpClient in dotnet core?

Tags:

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?

like image 868
Tom Aalbers Avatar asked Oct 02 '16 12:10

Tom Aalbers


People also ask

What is PATCH in .NET core?

JSON Patch defines a JSON document structure for expressing a sequence of operations to apply to a JavaScript Object Notation (JSON) document. It is defined in RFC 6902.

What is http patch C#?

HTTP POST can support partial updates to a resource. But there is a separate PATCH method. This new HTTP method, PATCH, modifies an existing HTTP resource. The call to the Patch method is sufficient to partially update the corresponding properties of the Employee object in the list.


2 Answers

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
    }
}
like image 78
Tom Aalbers Avatar answered Sep 17 '22 14:09

Tom Aalbers


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);
    }
}
like image 33
diegosasw Avatar answered Sep 20 '22 14:09

diegosasw