Search code examples
javac#.netmultipart

POST multipart/mixed in .NET


Just what the title says, if it helps in any way I have this java code (multipart consists of json object and file):

// Construct a MultiPart
MultiPart multiPart = new MultiPart();

multiPart.bodyPart(new BodyPart(inParams, MediaType.APPLICATION_JSON_TYPE));
multiPart.bodyPart(new BodyPart(fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));

// POST the request
final ClientResponse clientResp = resource.type("multipart/mixed").post(ClientResponse.class, multiPart);

(using com.sun.jersey.multipart ) and I want to create the same in .NET (C#)

So far I managed to POST the json object like this:

Uri myUri = new Uri("http://srezWebServices/rest/ws0/test");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
httpWebRequest.Proxy = null;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
Console.Write("START!");

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){
                string json = new JavaScriptSerializer().Serialize(new
                {
                    wsId = "0",
                    accessId = "101",
                    accessCode = "x@ds!2"
                });

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}

But I want to send the file together. The content type has to be "multipart/mixed" because that's what the web service gets. I tried to find some package that supports multiparts but I found nothing except maybe this http://www.example-code.com/csharp/mime_multipartMixed.asp (which is not free so I can't use it).


Solution

  • I finally managed to do it like this:

            HttpContent stringStreamContent = new StringContent(json);
            stringStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpContent fileStreamContent = new StreamContent(fileStream);
            fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    
            // Construct a MultiPart
            // 1st : JSON Object with IN parameters
            // 2nd : Octet Stream with file to upload
            var content = new MultipartContent("mixed");
            content.Add(stringStreamContent);
            content.Add(fileStreamContent);
    
            // POST the request as "multipart/mixed"
            var result = client.PostAsync(myUrl, content).Result;