MichaelCleverly
MichaelCleverly

Reputation: 2543

HttpClient's PutAsync behaving differently than a manual PUT request (via PostMan)

I'm trying to create a PUT request to an external API, with an array of integers as request body. When posting to the external API in question directly through PostMan (Chrome extension), it works fine. Here is the request:

PUT /rest/*****?skipconfig=true HTTP/1.1
Host: ******:****
Authorization: Basic **********
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache

[1214186,1214052,1214333,1213983,1214332,1214332]

However, when I try to create that same request with .NET's HttpClient, the external API throws a Server error 500 after about 10 seconds, making me suspect that the HttpClient has altered the request in some obscure way, that makes the external API read the request wrong. Here is my sample code:

    var json = JsonConvert.SerializeObject(intArray);

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", SvcCredentials);

    var content = new StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType); 

    // List data response.
    var uri = new Uri(BaseUrl + "/rest/*****?skipconfig=true", UriKind.Absolute);
    HttpResponseMessage response = await client.PutAsync(uri, content);
    if (response.IsSuccessStatusCode)
    {
        // Parse the response body.
        return response.Content.ReadAsAsync<object>().ToString();
    }
    throw new Exception(response.StatusCode.ToString());

What am I missing here? I've tried envoking the PutAsync method with both URI object and URL-string.

Upvotes: 0

Views: 1120

Answers (1)

MichaelCleverly
MichaelCleverly

Reputation: 2543

Alright, so I found the cause of this issue.

After doing a bit of research, I was able to decrypt the HTTPS request, using a simple option in fiddler.

As it turns out, StringContent(json, Encoding.UTF8, MediaTypeHeaderValue.Parse("application/json; charset=utf-8").MediaType); adds a "Content-Length" header behind the scenes. This header was the cause of the server error in the other end (don't ask me why).

Upvotes: 1

Related Questions