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

2019-07-17 20:49发布

问题:

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?

回答1:

Got this working with

ByteArrayContent byteContent = new ByteArrayContent(allContentBytes);
byteContent.Headers.Remove("Content-Type");
byteContent.Headers.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryaYcxA3wAp5XMUV2w");