Iskander Raimbaev
Iskander Raimbaev

Reputation: 1362

Strange behavior in HttpRequestMessage's Content-Type header

I tried to make HTTP POST request with application/json in body to an external web-service from C# (.NET Core 2.2.104).

I've already read all similar questions in SO and wrote this code:

            SignXmlRequestDto requestBody = new SignXmlRequestDto(p12, model.SignCertPin, model.Data);
            string json = JsonConvert.SerializeObject(requestBody);

            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = ncanNodeUrl,
                Headers =
            {
                { HttpRequestHeader.ContentType.ToString(), "application/json" }
            },
                Content = new StringContent(JsonConvert.SerializeObject(json))
            };

            var response = await httpClient.SendAsync(httpRequestMessage);

            string responseString = await response.Content.ReadAsStringAsync();

I am getting an error from service, it says: "Invalid header Content-Type. Please set Content-Type to application/json". What is interesting here, if I simulate this request from Postman, then everything work well and I get successful response. enter image description here

Updated: as @Kristóf Tóth suggested, I modified my code to:

            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = ncanNodeUrl,
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            };

            var response = await httpClient.SendAsync(httpRequestMessage);

            string responseString = await response.Content.ReadAsStringAsync();

but it still gives me the same error message.

Upvotes: 0

Views: 1238

Answers (2)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131189

Content-Type is a content header. It should be set on the content, not the request itself. This can be done either using the StringContent(string,Encoding,string) constructor :

Content = new StringContent(JsonConvert.SerializeObject(json),Encoding.UTF8, "application/json")

or by setting the StringContent's Headers.ContentType property :

var content=new StringContent(JsonConvert.SerializeObject(json));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Upvotes: 4

Kristóf Tóth
Kristóf Tóth

Reputation: 821

This might be an encoding issue. You should use JsonContent not StringContent OR you can do something similar:

// Serialize into JSON String
var stringPayload = JsonConvert.SerializeObject(payload);

// Wrap JSON StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

Upvotes: 2

Related Questions