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?
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.
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.
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:
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.
Got this working with
ByteArrayContent byteContent = new ByteArrayContent(allContentBytes);
byteContent.Headers.Remove("Content-Type");
byteContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With