HttpContentMultipartExtensions: Disposing MimeBodyParts

Topics: ASP.NET Web API
Jul 12, 2012 at 3:16 PM

I'm using the ReadAsMultipartAsync<T> extension method on HttpContent, where T is a MultipartFormDataStreamProvider.

My question is why does the method that adds the parsed MIME part's HttpContent to the StreamProvider (CheckPartCompletion in HttpContentMultipartExtensions) disposes the part right after that?

If a body part is a file, the MultipartFormDataStreamProvider returns a FileStream, which gets disposed by the MimeBodyPart. This means that by the time the task returned by ReadAsMultipartAsync completes, I can't read the file from the form data, because its FileStream has already been disposed.

I have tried using MultipartMemoryStreamProvider and it works, but only because MimeBodyPart's Dispose only disposes its stream if it's not a MemoryStream. Since I need to handle large file uploads, MemoryStream is not an option.

Is this a bug, and if not, how should I handle file uploads with MultipartFormDataStreamProvider?

Jul 15, 2012 at 8:36 AM

When the ReadAsMultipartAsync completes you can get the file names of the saved files from the MultipartFormDataStreamProvider.FileData property. Just open the files as normal and you can read and process them as you wish.

Henrik

Jul 16, 2012 at 8:55 AM

Hi Henrik,

This actually makes perfect sense, it's just that I couldn't figure it out from the code alone.

Thanks!