9

I'm trying to set a Content-Type header in a c# HttpClient request of "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w".

So far I've tried using TryAddWithoutValidation which does not throw any exception/error but when I watch the request in fiddler its just not added? See code below.

client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
response = client.PostAsync("https://example.com", byteContent).Result;

I've also tried converting the byte array I'm trying to send to a string and using StringContent but this throws an exception saying "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w" is invalid.

StringContent testStringcontent = new StringContent(Encoding.Default.GetString(allContentBytes), Encoding.UTF8, "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
response = client.PostAsync("https://example.com", testStringcontent).Result;

I've tried all the similar questions suggestions and can't see to get any to send the header or not throw some sort of exception. Should I abandon this and use web client which I'm told is more flexible?

Mr J
  • 2,655
  • 4
  • 37
  • 58
  • Does this answer your question? [How do you set the Content-Type header for an HttpClient request?](https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request) – Ian Kemp Feb 04 '20 at 07:49

1 Answers1

16

Got this working with

ByteArrayContent byteContent = new ByteArrayContent(allContentBytes);
byteContent.Headers.Remove("Content-Type");
byteContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
Mr J
  • 2,655
  • 4
  • 37
  • 58