C# – httpclient – how to set Content-Disposition to “application/json;” in a multipart

cdotnet-httpclientmultipartwindows-phone-8

Using System.Net.Http.Httpclient, I am trying to do a multipart post in C# and with a wp8.

This is a snippet of my code:

varclient = new HttpClient();

client.DefaultRequestHeaders.TryAddWithoutValidation(    
"Content-Type", "application/json");

content = new MultipartFormDataContent();
content.Add(new StringContent(requestObj, Encoding.UTF8, "application/json"), "request");

but using Fiddler, I noticed that I am sending this:

Content-Disposition: form-data; name=request

Content-Type: text/plain; charset=utf-8

while I need to send this (taken from an android device where the call is working):

Content-Disposition: application/json; name="request"

Content-Type: text/plain; charset=UTF-8

  • How to achieve the expected result?

Best Answer

What about:

setting the header on the HttpContent using TryAddWithoutValidation

and changing the MultipartFormDataContent into a MultipartContent object:

var content = new MultipartContent();

var contentData = new StringContent(requestObj, Encoding.UTF8, "application/json");
contentData.Headers.TryAddWithoutValidation("Content-Disposition", "application/json name=request");
content.Add(contentData);

This results in these headers

POST http://www.directupload.net/index.php?mode=upload HTTP/1.1
Content-Type: multipart/mixed; boundary="6905763f-e85a-44f9-b7f4-8967b357addf"
Host: www.directupload.net
Content-Length: 274
Expect: 100-continue
Connection: Keep-Alive

--6905763f-e85a-44f9-b7f4-8967b357addf
Content-Type: application/json; charset=utf-8
Content-Disposition: application/json name=request

{    "id": 1,    "name": "A green door",    "price": 12.50,    "tags": ["home", "green"]}
--6905763f-e85a-44f9-b7f4-8967b357addf--