How to execute patch request using HttpClient in dotnet core?

I am trying to create a Patch request with HttpClient in the dotnet core. I found other methods

 using (var client = new HttpClient()) { client.GetAsync("/posts"); client.PostAsync("/posts", ...); client.PutAsync("/posts", ...); client.DeleteAsync("/posts"); } 

but cannot find the Patch option. Is it possible to execute a Patch request using HttpClient ? If so, can someone show me an example of how to do this?

+11
source share
3 answers

Thanks to the commentary of Daniel A. White, I got the following works.

 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 } } 
+12
source

HttpClient does not have a patch out of the box. Just 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); } } 
+2
source

Starting with .Net Core 2.1, PatchAsync() now available for HttpClient

Snapshot for applies to

Link: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync

+1
source

Source: https://habr.com/ru/post/1257609/


All Articles