我正在使用 asp.net core 并使用 C# 进行编程。
我在 Controller 中有一个方法可以从 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);
}
}
}
155kb已上传成功;但是,3.38 MB 的文件失败:
System.ObjectDisposeException:“无法访问已关闭的文件。”
我读到该问题可能与限制和流处理有关;然而,尽管添加了我所看到的堆栈溢出建议的修复程序,但问题仍然存在,例如:
[HttpPost、DisableRequestSizeLimit、RequestFormLimits(MultipartBodyLengthLimit = Int32.MaxValue、ValueLengthLimit = Int32.MaxValue、ValueCountLimit = Int32.MaxValue)]
欢迎任何建议:)谢谢!
最佳答案
由于使用async void
,您遇到了竞争情况。由于 void
返回类型,运行应用的服务器代码无法知道您的方法何时完成并立即处理请求。
使用 Task
作为 UploadFile
方法的返回类型。
使用 async
时,通常应避免 void
返回类型。
See the article from Microsoft for more infos
关于c# - 文件上传asp.net core - System.ObjectDisposeException : 'Cannot access a closed file.' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67971199/