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?
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.
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.
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
}
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With