"Cannot access a closed file." 在 .Net Core 3 中将文件上传到 Azure Blob 存储时

"Cannot access a closed file." When upload a file to Azure Blob Storage in .Net Core 3

我正在尝试将文件上传到 Azure Blob 存储,但收到以下消息:

“无法访问已关闭的文件”

这是随机的,如果我尝试加载同一张图片两次,第一次可能会加载,第二次可能会出错

这是我的上传功能

private async Task<string> UploadResizedToStorage(IFormFile file, string fileName, int thumbnailWidth, IImageEncoder encoder)
    {
        try
        {
            using MemoryStream streamReader = new MemoryStream();
            await file.CopyToAsync(streamReader);
            var accountName = _config.GetValue<string>("AzureStorage:AccountName");
            var accountKey = _config.GetValue<string>("AzureStorage:AccountKey");
            var imgContainer = _config.GetValue<string>("AzureStorage:ImageContainer");
            var storageCredentials = new StorageCredentials(accountName, accountKey);
            var storageAccount = new CloudStorageAccount(storageCredentials, true);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(imgContainer);
            var blockBlob = container.GetBlockBlobReference(fileName);
            streamReader.Position = 0;
            await blockBlob.UploadFromStreamAsync(streamReader, streamReader.Length);
            return blockBlob.SnapshotQualifiedStorageUri.PrimaryUri.ToString();
        }
        catch(Exception e)
        {
            _logger.LogError("UploadResizedToStorage "+
                               e.Message+
                             " Arquivo:"+
                             fileName);
            return "";
        }
        
    }

该应用程序托管在 Docker 上,通过 Azure 应用程序服务

错误

2021-06-25T18:00:20.174050985Z: [INFO]  [41m[30mfail[39m[22m[49m: ruralbackend.Service.StorageAzure[0]
2021-06-25T18:00:20.174102685Z: [INFO]        UploadResizedToStorage Cannot access a closed file. Arquivo:46-6.jpg

这可能是因为您的 MemoryStream(出于某种原因)正在关闭 before/during UploadFromStreamAsync 方法的执行。

删除 using 关键字并在执行结束时在 finally 块中手动处理 streamReader 对象。这将确保流仅在完全达到其目的时才被释放。