Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't send Content-Type header with c# HttpClient

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?

like image 713
Mr J Avatar asked Nov 18 '16 14:11

Mr J


People also ask

What is a Content Type header used for?

Content-Type The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending). In responses, a Content-Type header tells the client what the content type of the returned content actually is.

How to set the Content-Type header for a GET request?

Therefore, as others have indicated, the preferred way to set the Content-Type header is through the HttpContent.Headers.ContentType property. With that said, certain APIs (such as the LiquidFiles Api, as of 2016-12-19) requires setting the Content-Type header for a GET request.

Is it possible to add a header without a hyphen?

but this gives a useless header named ContentType, without the hyphen. Header names are not case-sensitive, but are very hyphen-sensitive. You have to declare the encoding and type of the body when adding the body to the Content part of the http request:

What is content type content type?

Content-Type. The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending). In responses, a Content-Type header tells the client what the content type of the returned content actually is.


1 Answers

Got this working with

ByteArrayContent byteContent = new ByteArrayContent(allContentBytes);
byteContent.Headers.Remove("Content-Type");
byteContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
like image 69
Mr J Avatar answered Oct 03 '22 00:10

Mr J