c# - 如何删除 HttpClient 请求 header C# 中的默认字符集

标签 c# asp.net-web-api encoding utf-8 httpclient

我正在尝试从 C# 代码中调用一个 API。我无法获得响应并收到状态代码“500 - 内部服务器错误”。

找到了“Charset-UTF8”被附加到请求 header 中的原因

当我尝试在没有“Charset-UTF8”的情况下访问 Fiddler 中的 API 时,我能够在 Fiddler 和 postman 中获得响应。使用“Charset-UTF8”我得到了同样的 500 内部服务器错误。内容类型是 application/json

我什至尝试了每种字符集编码方法 UTF-8、16、32、unicode 和 C# 代码中的默认格式,给出了相同的错误。

请告诉我如何从 API 请求 header 中删除 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);
    });

最佳答案

尝试下面的解决方案

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 上测试

关于c# - 如何删除 HttpClient 请求 header C# 中的默认字符集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44389533/

相关文章:

c# - 选中复选框时更改 wpf 数据网格行背景颜色

C# 非常简单的图像缩放器

javascript - 使用用于过滤 EF 的 WEB API OData 服务自定义 DataTables - 列搜索不起作用

c# - 在其他线程中创建Wpf用户控件

url - Web Api:Whitespace使ASP.NET 4 Web Api(RC)崩溃

python - 在 Python 中读取 .dic 文件

c# - ASP.NET WebAPI 返回 Http 405

javascript - jQuery自动完成发送出奇怪的字符

encoding - 相同类型的 base64 编码二进制数据是否具有相同的 header ?

asp.net - 英镑符号 (£) 从 ASP.NET 字符串中消失