HTTP PATCH Method C#

Ravi Shastri picture Ravi Shastri · Jun 7, 2017 · Viewed 9.2k times · Source

I don't see the option of including a HTTP "PATCH" request, I don't get the option using Visual Studio Intellisense? How do I include the "PATCH" method in this code instead of "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");
}

Answer

Dennis Larisch picture Dennis Larisch · Jun 7, 2017

I found this post here on StackOverflow: click

He has done it with the folowing code example:

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