September 6, 2012

Adding PATCH support to HttpClient

I’m not going to go into a lot of detail here. Quite simple, the ASP.NET Web API HttpClient doesn’t include PATCH support out of the box or rather we don’t have nice extension methods for doing so. So here you go:

    public static Task<HttpResponseMessage> PatchAsJsonAsync<T>(this HttpClient client, string requestUri, T value)
    {
        Ensure.Argument.NotNull(client, "client");
        Ensure.Argument.NotNullOrEmpty(requestUri, "requestUri");
        Ensure.Argument.NotNull(value, "value");

        var content = new ObjectContent<T>(value, new JsonMediaTypeFormatter());
        var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri) { Content = content };

        return client.SendAsync(request);
    }

If you need to pass a cancellation token or a specific formatter then you can create an overload for that. The above is all I need for now.

© 2020 Ben Foster