Search code examples
c#asp.net-corehttp-headers

C# HttpRequestMessage - Host ignores the Content-Type Header I send it and complains that I am sending the wrong Content Type


I need to send a POST request to a website to authenticate myself with an empty body. I am getting the following message back even though I set my headers to send content type of application/json.

{"messages":[{"message":"Invalid content type (text/plain). These are valid: application/json","code":"1708"}],"response":{}}

Code:

...
var client = new HttpClient(handler);

string token = "...";

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

var httpRequestMessage = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("..."),
    Headers = {
                    { HttpRequestHeader.Authorization.ToString(), "Basic " + token },
                    { HttpRequestHeader.ContentType.ToString(), "application/json" },
                    { HttpRequestHeader.ContentLength.ToString(), "0"}
              },
    Content = new StringContent(string.Empty)
};

var response = await client.SendAsync(httpRequestMessage);
var contents = await response.Content.ReadAsStringAsync();
...

The documentation shows to include an empty set of curly braces but when I sent "{}" (string) or Content = {} I get Invalid content type (application/octet) instead.

enter image description here

What can I do to get the correct content type?


Solution

  • You can add the content type like below:

    var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("..."),
        Content = new StringContent("{}", Encoding.UTF8, "application/json") // Send an empty JSON object with the correct content type
    };