我正在尝试使用dotnet核心中的Patch
创建HttpClient
请求。我找到了其他方法,
using (var client = new HttpClient())
{
client.GetAsync("/posts");
client.PostAsync("/posts", ...);
client.PutAsync("/posts", ...);
client.DeleteAsync("/posts");
}
但似乎无法找到Patch
选项。是否可以使用Patch
执行HttpClient
请求?如果是这样,有人能告诉我一个如何做的例子吗?
答案 0 :(得分:11)
感谢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 :(得分: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);
}
}
答案 2 :(得分:1)
从.Net Core 2.1开始,PatchAsync()
现在可用于HttpClient
参考: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.patchasync