How to set WebClient Content-Type Header?

ぐ巨炮叔叔 提交于 2019-12-30 03:44:04

问题


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.

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.

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

EDIT CopyHeaderTo 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.


回答1:


You could try adding to the Headers collection.

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



回答2:


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



回答3:


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 link explain that.

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



回答4:


Well, I just missed Request.ContentType property. If GetWebRequest method is overridden, setting ContentType to whatever value desired does it.

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



来源:https://stackoverflow.com/questions/1595956/how-to-set-webclient-content-type-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!