Sending PATCH request using WebClient in .NET

I have an older ASP.NET WebForms site. I am trying to use WebClient to send a PATCH request to a REST API:

using (WebClient client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + authToken;
    try
    {
        responseString = Encoding.UTF8.GetString(client.UploadValues(endpoint, "PATCH", body));
    }                
    catch (Exception e)
    {
        return e;
    }            
}

In this snippet, endpoint is the URI I’m PATCH-ing to, and body is a NameValueCollection.

This gives me an HTTP 400 “Bad Request” error. If I drill down in the exception, it indicates a protocol violation. I have tried adding a header for content-type, but that did not help.

This same code does work for POST requests, and it’s how I’m getting my access token successfully. But it does not work for PATCH. Is there any way to send a valid PATCH request using WebClient?

I realize there are other libraries out there, but if possible, I’d like to be consistent with the rest of the code in this class in using WebClient. If I have to switch to something else, I’d want to update the rest of the code too.

Update

Yes, the API does support PATCH. It’s the Microsoft Graph API and PATCH works fine with Postman.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It looks ok. If the API supports PATCH you should receive a response.
Could you check if PATCH is implemented on the API?

Another possibility is that you violate some validation rules applied in PATCH method.

Method 2

I got it to work using the UploadString method, as follows:

using (WebClient client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + authToken;
    try
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        responseString = client.UploadString(endpoint, method, body);
    }                
    catch (Exception e)
    {
        return e;
    }            
}

Where body is a JSON-formatted string, instead of a NameValueCollection as I was trying initially. I’m not sure if there’s a better way to do this, but it seems to be working now.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x