How do I do a patch request using HttpClient in dotnet core?
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);
}
}
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: This is old. See @LxL answer.
As of Feb 2022
###Original Answer###
As of .Net Core 2.1, the PatchAsync()
is now available for HttpClient
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync