问题描述
我正在尝试访问来自C#
的API
代码。我无法获得响应并收到状态代码"500-内部服务器错误"。
找到请求标头中追加Charset-UTF8
的原因
当我尝试在Fiddler中点击API而不使用"Charset-UTF8
"时,我能够在Fiddler和Postman中得到响应。使用"Charset-UTF8
"时,我得到相同的500内部服务器错误。内容类型为application/json
。
我甚至尝试了每种字符集编码方法UTF-8、16、32、Unicode和C#代码的默认格式,都给出了同样的错误。
请告诉我如何从API请求头中删除(追加)字符集。
请仔细阅读我附加的代码
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);
});
推荐答案
尝试下面的解决方案
content.Headers.Remove("Content-Type"); // "{application/json; charset=utf-8}"
content.Headers.Add("Content-Type", "application/json");
或
content.Headers.ContentType.CharSet = string.Empty;
我已在dotnet/corefx
回购上提交了一个问题。
查看https://github.com/dotnet/corefx/issues/25290
在.NET Core 2.0,.NET Standard 2.0上测试