问题
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