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

问题描述 投票:8回答:2

我试图用dotnet核心中的Patch创建一个HttpClient请求。我找到了其他方法,

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

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

dotnet-httpclient http-patch
2个回答
13
投票

感谢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
    }
}

1
投票

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.