如何在dotnet核心中使用HttpClient进行补丁请求?

Tom*_*ers 11 dotnet-httpclient http-patch

我正在尝试Patch使用HttpClientin dotnet核心创建一个请求.我找到了其他方法,

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

但似乎无法找到Patch选项.可以PatchHttpClient?做请求吗?如果是这样,有人能告诉我一个如何做的例子吗?

Tom*_*ers 12

感谢Daniel A. White的评论,我得到了以下工作.

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用“HttpMethod.Patch”而不是“PATCH”。 (4认同)
  • 您在哪里添加身体? (3认同)
  • @DanielGatti 是对的。您要发送什么作为 PATCH 的正文?我所做的是将它添加到对象中。request.Content = new StringContent(jsonString, Encoding.UTF8, "applicantion/json"); (3认同)

LxL*_*LxL 7

截至 2022 年 2 月 2022 年更新

###原答案###

从 .Net Core 2.1 开始,PatchAsync()现在可用于HttpClient

快照适用于

参考: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync


ibe*_*dev 6

HttpClient 没有开箱即用的补丁。简单地做这样的事情:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)