CMNagaraj
CMNagaraj

Reputation: 71

How to remove the default charset in HttpClient Request Header C#

I am trying to hit an API from C# code. I am unable to get the response and receiving the status code "500 - Internal Server error".

Found the reason that the "Charset-UTF8" is getting appended in the request header

When i tried to hit the API in Fiddler without "Charset-UTF8", I am able to get the response in Fiddler and postman. With the "Charset-UTF8" i get the same 500 internal server error. The content type is application/json.

I even tried each and every charaset encoding methods UTF-8,16,32, unicode and default format from C# code, gives the same error.

Please let me know how to remove the CharSet(appending) from the API request Header.

please go through code i have attached

HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("i have third party url");
client1.DefaultRequestHeaders
    .Accept
    .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
        client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(
                System.Text.ASCIIEncoding.ASCII.GetBytes(
                    string.Format("{0}:{1}", userName, password))));

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, client1.BaseAddress);


StringContent content = new StringContent(JsonConvert.SerializeObject("working request"));


request.Content = content;

client1.SendAsync(request)
    .ContinueWith(responseTask =>
    {
        Console.WriteLine("Response: {0}", responseTask.Result);
    });

Upvotes: 6

Views: 9402

Answers (2)

pkucas
pkucas

Reputation: 187

If you want to remove the client request headers outside of the request:

myClient.DefaultRequestHeaders.Remove("Connection");
myClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
myClient.DefaultRequestHeaders.Accept.Remove(new MediaTypeWithQualityHeaderValue("application/json"));
myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Upvotes: 0

Hung Quach
Hung Quach

Reputation: 2177

Try the solution below

content.Headers.Remove("Content-Type"); // "{application/json; charset=utf-8}"
content.Headers.Add("Content-Type", "application/json");

or

content.Headers.ContentType.CharSet = string.Empty;

I have submitted an issue on dotnet/corefx repo.

Check it out https://github.com/dotnet/corefx/issues/25290

Tested on .NET Core 2.0, .NET Standard 2.0

Upvotes: 8

Related Questions