juststressed
juststressed

Reputation: 89

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

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!

Upvotes: 2

Views: 1774

Answers (2)

Lucas
Lucas

Reputation: 423

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

Upvotes: 5

Jeremy C.
Jeremy C.

Reputation: 86

A possible fix is documented in this thread: https://forums.asp.net/t/1397944.aspx?+Cannot+access+a+closed+file.

Specifically, changing the value of 'requestLengthDiskThreshold' in your web config.

<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="20000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>
</system.web>

A similar fix is mentioned @ System.ObjectDisposedException: Cannot access a closed Stream

Upvotes: 0

Related Questions