1

I am trying to upload a multi part file, but I keep getting the following exception when reading the content of the Http request

IOException: Unexpected end of Stream, the content may have already been read by another component.

I followed the example described in the project from ASP.NET samples, here is what my controller method looks like:

        [HttpPost("LoadMultipart")]
        [DisableFormValueModelBinding]
        public void UploadMultipartUsingReader()
        {
            string boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), DEFAULT_FORM_OPTIONS.MultipartBoundaryLengthLimit);
            MultipartReader reader = new MultipartReader(boundary, HttpContext.Request.Body);

            int totalBytes = 0;
            MultipartSection section;

            while ((section = reader.ReadNextSectionAsync().Result) != null) // This line causes the exception to be thrown
            {
                ContentDispositionHeaderValue contentDispo = section.GetContentDispositionHeader();

                if (contentDispo.IsFileDisposition())
                {
                    FileMultipartSection fileSection = section.AsFileSection();
                    int bufferSize = 32 * 1024;
                    totalBytes = ReadStream(fileSection.FileStream, bufferSize);
                }
                else if (contentDispo.IsFormDisposition())
                {
                    FormMultipartSection formSection = section.AsFormDataSection();
                    string value = formSection.GetValueAsync().Result;
                }
            }
         }

I have broswed lots of forums and documentations to troobleshoot this issue, and from what I understood what goes wrong is that maybe the framework automatically binds the data into a model and therefore consumes the steam to the request data, which is something that should be disabled thanks to the [DisableFormValueModelBinding] flag, so I'm quite confused now.

Thanks for any insight

Toto
  • 736
  • 9
  • 33

0 Answers0