HTTP PATCH方法C#

时间:2017-06-07 18:22:06

标签: c# httpclient http-patch

我没有看到包含HTTP" PATCH"请求,我没有使用Visual Studio Intellisense获得选项?如何包含" PATCH"此代码中的方法而不是" POST"

using (HttpClient httpClient = new HttpClient())
{
    Uri requesturi = new Uri(string.Format("{0}/api/data/v8.2/", url));
    httpClient.BaseAddress = requesturi;
    httpClient.Timeout = new TimeSpan(0, 0, 4);  // 10 minutes
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    result = GetS2SAccessToken(url, pwd);
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
    httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
    httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "");                   
    request.Content = new StringContent(props.ToString(), Encoding.UTF8, "application/json");
}

1 个答案:

答案 0 :(得分:0)

我在StackOverflow上找到了这篇文章:click

他已经完成了下面的代码示例:

public async Task<HttpResponseMessage> PatchAsync(HttpClient client, Uri requestUri, IHttpContent iContent) {
    var method = new HttpMethod("PATCH");

    var request = new HttpRequestMessage(method, requestUri) {
        Content = iContent
    };

    HttpResponseMessage response = new HttpResponseMessage();
    // In case you want to set a timeout
    //CancellationToken cancellationToken = new CancellationTokenSource(60).Token;

    try {
         response = await client.SendRequestAsync(request);
         // If you want to use the timeout you set
         //response = await client.SendRequestAsync(request).AsTask(cancellationToken);
    } catch(TaskCanceledException e) {
        Debug.WriteLine("ERROR: " + e.ToString());
    }

    return response;
}