我正在尝试从API
代码中点击C#
。我无法收到回复并收到状态码" 500 - 内部服务器错误"。
找到" Charset-UTF8
"正在附加在请求标题中
当我试图在没有" Charset-UTF8
"的情况下点击Fiddler中的API时,我能够在Fiddler和postman中得到答案。使用" Charset-UTF8
"我得到相同的500内部服务器错误。内容类型为application/json
。
我甚至尝试了每个charaset编码方法UTF-8,16,32,unicode和C#代码的默认格式,给出了同样的错误。
请告诉我如何从API请求标题中删除CharSet(附加)。
请查看我附上的代码
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);
});
答案 0 :(得分:3)
尝试以下解决方案
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
repo上提交了一个问题。
查看https://github.com/dotnet/corefx/issues/25290
经过测试 .NET Core 2.0,.NET Standard 2.0
答案 1 :(得分:0)
如果要在请求之外删除客户端请求标头:
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"));