44

How I can set a header in the webClient class? I tried:

client.Headers["Content-Type"] = "image/jpeg";

that throws a WebException

My code:

WebClient client = new WebClient();
client.Headers.Set("Content-Type", "image/png");
client.Headers.Set("Content-Length", length);
client.Headers.Add("Slug", name);
NameValueCollection nvc = new NameValueCollection();
nvc.Add("file", FileContents);

Byte[] data = client.UploadValues(url, nvc);
string res = Encoding.ASCII.GetString(data);
Response.Write(res);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
The Mask
  • 17,007
  • 37
  • 111
  • 185

4 Answers4

54

If the header already exists:

client.Headers.Set("Content-Type", "image/jpeg");

if its a new header:

client.Headers.Add("Content-Type", "image/jpeg");

Also, there is a chance that you are getting an error because you are trying to set the headers too late. Post your exception so we can let you know.

Update

Looks like there are some weird restrictions on the "Content-Type" header with the WebClient class. Look in to using the client.Download methods (DownloadData, DownloadFile, etc...)

See if using the "UploadFile" method on webclient works rather than doing it manually. It returns the respose body byte[].

If you continue to have issues with the WebClient, try justing using a plain old HttpRequest/HttpWebRequest.

jdc0589
  • 6,972
  • 5
  • 36
  • 39
17

It seems you can not set Content-type with WebClient.UploadValues method. You could set Content-type with WebClient.UploadData method

Use something like,

Client.Headers["Content-Type"] = "application/json";
Client.UploadData("http://www.imageshack.us/upload_api.php", "POST", Encoding.Default.GetBytes("{\"Data\": \"Test\"}"));
SajithK
  • 1,014
  • 12
  • 23
2

You cannot change the Content-Type if you use the UploadValues method, it must be application/x-www-form-urlencoded, see webclient source code enter image description here

syb
  • 369
  • 2
  • 5
2

Have you tried this syntax: client.Headers.Add("Content-Type", "image/jpeg");

What's your stack trace? At what point are you setting this? And what version of IIS/OS are you running under?

Xavier Egea
  • 4,712
  • 3
  • 25
  • 39
Mrchief
  • 75,126
  • 20
  • 142
  • 189