20

我正在尝试使用in dotnet core创建一个Patch请求。HttpClient我找到了其他方法,

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

但似乎找不到Patch选项。是否可以使用Patch请求HttpClient?如果是这样,有人可以告诉我一个例子吗?

4

3 回答 3

21

感谢 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
    }
}
于 2016-10-02T13:37:11.140 回答
9

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);
    }
}
于 2019-03-08T17:30:55.180 回答
4

截至 2022 年 2 月 2022 年更新

###原答案###

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

快照适用于

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

于 2019-09-03T21:57:06.753 回答