Reputation: 4934
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?
Upvotes: 33
Views: 39810
Reputation: 1548
As of Feb 2024, You can just specify Method = Patch.
var request = new HttpRequestMessage()
{
RequestUri = new Uri(url),
Method = HttpMethod.Patch,
Content = new FormUrlEncodedContent(requestData)
};
var response = await client.SendAsync(request);
Send request data as Dictionary<string, string>.
Upvotes: 0
Reputation: 4934
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.
Upvotes: 36
Reputation: 1948
###Original Answer###
As of .Net Core 2.1, the PatchAsync()
is now available for HttpClient
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync
Upvotes: 7
Reputation: 15694
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);
}
}
Upvotes: 12