C# 如何设置 WebClient Content-Type Header?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1595956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:10:36  来源:igfitidea点击:

How to set WebClient Content-Type Header?

c#content-typewebclient

提问by MaLKaV_eS

To conect to a third party service I need to make a Https Post. One of the requisites set is to sent a custom content type.

要连接到第三方服务,我需要制作一个 Https 帖子。必要条件之一是发送自定义内容类型。

I'm using WebClient, but I can't find how to set it. I've tried making a new class and overriding the CreateRequest Method, but that make request crash.

我正在使用 WebClient,但我找不到如何设置它。我已经尝试创建一个新类并覆盖 CreateRequest 方法,但这会使请求崩溃。

Is there any way to do that without having to rewrite CopyHeadersTo method?

有什么方法可以做到这一点而不必重写 CopyHeadersTo 方法?

EDITCopyHeaderTo is a method I've seen using .NET Reflector. It's invoked from GetWebRequest and sets all Request Headers, including Content-Type, from private properties.

EDITCopyHeaderTo 是我见过的一种使用 .NET Reflector 的方法。它从 GetWebRequest 调用并从私有属性设置所有请求标头,包括 Content-Type。

采纳答案by MaLKaV_eS

Well, I just missed Request.ContentTypeproperty. If GetWebRequestmethod is overridden, setting ContentTypeto whatever value desired does it.

好吧,我只是错过了Request.ContentType财产。如果GetWebRequest方法被覆盖,则设置ContentType为所需的任何值。

Still, connection to third party is not working. Go figure.

尽管如此,与第三方的连接不起作用。去搞清楚。

回答by Darin Dimitrov

You could try adding to the Headerscollection.

您可以尝试添加到Headers集合中。

myWebClient.Headers.Add("Content-Type","application/xxx");

回答by V K

webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

回答by bob dawson

I encounter this too. And found that you must use Client Http, otherwise Browser Http will block change of Content-Type for security reason. This MSDN linkexplain that.

我也遇到这个。并发现必须使用Client Http,否则Browser Http出于安全原因会阻止Content-Type的更改。 这个 MSDN 链接解释了这一点。

WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
client.Headers["Content-Type"] = "application/json";