File upload asp.net core - System.ObjectDisposedException: 'Cannot access a closed file.'

Viewed 588

I am using asp.net core and programming in C#.

I have a method in a controller to upload a file from a form in a view.

public async void UploadFile([FromForm(Name = "aFile")] IformFile aFile)
{
   var filePath = Path.Combine(_webhost.WebRootPath, "Images", aFile.FileName);

   if (aFile.Length > 0)
   {
      using (FileStream fs = System.IO.File.Create(filePath))
      {
         await aFile.CopyToAsync(fs);
      }
   }
}

A 155kb uploaded successfully; however, a 3.38 MB file failed:

System.ObjectDisposedException: 'Cannot access a closed file.'

I have read that the issue may pertain to limits and stream disposal; however, the problem persists despite adding fixes I've seen recommended on stack overflow such as:

[HttpPost, DisableRequestSizeLimit, RequestFormLimits(MultipartBodyLengthLimit = Int32.MaxValue, ValueLengthLimit = Int32.MaxValue, ValueCountLimit = Int32.MaxValue)]

Any recommendations would be welcome :) thanks!

2 Answers

Your running into a race condition due to your usage of async void. Due to the void return type, the server code running your app can not know when your method finishes and disposes the request immediately.
Use Task as the return type of your UploadFile method.

You should generally avoid void return types when working with async.
See the article from Microsoft for more infos

Related