29

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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
MaLKaV_eS
  • 1,325
  • 3
  • 23
  • 39

4 Answers4

47

You could try adding to the Headers collection.

myWebClient.Headers.Add("Content-Type","application/xxx");
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    That throws a WebException, saying that Content-Type cannot be changed for current petition. – MaLKaV_eS Oct 21 '09 at 07:02
  • 1
    Who throws this exception? Is it the server script you are posting to? I have tested the example provided in MSDN and it successfully set the Content-Type header to a custom value. – Darin Dimitrov Oct 21 '09 at 09:04
  • 2
    I had to do this: _client.Headers["Content-Type"] = "application/Json" Still not working correctly, but at least it compiles! Working in silverlight 5. – RaoulRubin Nov 17 '11 at 16:25
  • 1
    Just wondering.. should you have called myWebClient.Headers.Remove("Content-Type") or maybe on a broader level called myWebClient.Headers.Clear() first before setting/Adding Content-Type? – Dinesh Rajan Feb 14 '14 at 15:57
15
webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
V K
  • 1,645
  • 3
  • 26
  • 57
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.

JYelton
  • 35,664
  • 27
  • 132
  • 191
MaLKaV_eS
  • 1,325
  • 3
  • 23
  • 39
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";
bob dawson
  • 91
  • 5