使用HttpClient时如何在Content-Type中排除字符集? [英] How do I not exclude charset in Content-Type when using HttpClient?

查看:121
本文介绍了使用HttpClient时如何在Content-Type中排除字符集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在.net核心项目中使用HttpClient向对接受/返回JSON的REST服务发出GET请求。我不控制外部服务。

I am attempting to use HttpClient in a .net core project to make a GET request to a REST service that accepts/returns JSON. I don't control the external service.

无论如何尝试,我都无法弄清楚将Content-Type标头设置为application / json

No matter how I try, I can't figure out to set the Content-Type header to application/json only.

当我使用

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

它在HTTP GET请求中发送:

it sends in the HTTP GET request:

Content-Type: application/json; charset=utf-8

但是,此特定服务不适用于此功能。仅在标题为

However, this particular service does not work with this. It will only work if the header is:

Content-Type: application/json

我尝试设置标头而不进行验证,并且我在Web / SO上找到的所有方法都不适用于.net核心。 .net核心中没有其他所有用于发送HTTP请求的方法,因此我需要弄清楚这一点。如何在内容类型中排除字符集?

I've tried setting headers without validation, and all the approaches I've found on the web/SO doesn't apply to .net core. All the other the approaches to sending HTTP requests aren't available in .net core, so I need to figure this out. How can I exclude the charset in content-type?

通过变通方法进行编辑

如答案中所述,服务应使用Accept标头。解决方法(如Shaun Luttin在其答案中所述)是向GET添加一个空内容(什么?GET没有内容!是的...)。

As mentioned in the answers, the service should be using the Accept header. The workaround (as Shaun Luttin has in his answer) is to add an empty content to the GET (what? GETs don't have content! yeah...). It's not pretty, but it does work.

推荐答案

您正在设置接受标头。您需要改为设置 ContentType 标头,该标头仅适用于POST。

You're setting the Accept header. You need to set the ContentType header instead, which is only canonical for a POST.

var client = new HttpClient();
var content = new StringContent("myJson");
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var result = client.PostAsync("http://bigfont.ca", content).Result;

如果您确实要为GET设置,则可以执行以下操作:

If you really want to set it for a GET, you can do this:

var client = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, "http://www.bigfont.ca");
message.Content = new StringContent(string.Empty);
message.Content.Headers.Clear();
message.Content.Headers.Add("Content-Type", "application/json");
var result = client.SendAsync(message).Result;

这篇关于使用HttpClient时如何在Content-Type中排除字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆