简体   繁体   English

如何设置 WebClient Content-Type Header?

[英]How to set WebClient Content-Type Header?

To conect to a third party service I need to make a Https Post.要连接到第三方服务,我需要制作一个 Https 帖子。 One of the requisites set is to sent a custom content type.必要条件之一是发送自定义内容类型。

I'm using WebClient, but I can't find how to set it.我正在使用 WebClient,但我找不到如何设置它。 I've tried making a new class and overriding the CreateRequest Method, but that make request crash.我已经尝试创建一个新类并覆盖 CreateRequest 方法,但这会使请求崩溃。

Is there any way to do that without having to rewrite CopyHeadersTo method?有什么方法可以做到这一点而不必重写 CopyHeadersTo 方法?

EDIT CopyHeaderTo is a method I've seen using .NET Reflector. EDIT CopyHeaderTo 是我见过的一种使用 .NET Reflector 的方法。 It's invoked from GetWebRequest and sets all Request Headers, including Content-Type, from private properties.它从 GetWebRequest 调用并从私有属性设置所有请求标头,包括 Content-Type。

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

myWebClient.Headers.Add("Content-Type","application/xxx");
webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

Well, I just missed Request.ContentType property.好吧,我只是错过了Request.ContentType属性。 If GetWebRequest method is overridden, setting ContentType to whatever value desired does it.如果GetWebRequest方法被覆盖, GetWebRequest ContentType设置为所需的任何值。

Still, connection to third party is not working.尽管如此,与第三方的连接不起作用。 Go figure.去搞清楚。

I encounter this too.我也遇到这个。 And found that you must use Client Http, otherwise Browser Http will block change of Content-Type for security reason.并发现必须使用Client Http,否则Browser Http出于安全原因会阻止Content-Type的更改。 This MSDN link explain that. 这个 MSDN 链接解释了这一点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM