Подтвердить что ты не робот

Как выполнить запрос патча, используя HttpClient в ядре dotnet?

Я пытаюсь создать запрос Patch с HttpClient в ядре dotnet. Я нашел другие методы,

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

но не может найти опцию Patch. Возможно ли выполнить запрос Patch с помощью HttpClient? Если да, может ли кто-нибудь показать мне пример, как это сделать?

4b9b3361

Ответ 1

Благодаря комментарию 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
    }
}

Ответ 2

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);
    }
}