我有一个 ASP.NET Core 2.1 应用程序,但出现错误:
无法访问已处置的对象。对象名称:'Amazon.S3.AmazonS3Client'
尝试调用我的 AWS S3 读取对象服务时。该服务第一次工作,第二次及以后失败。
我在 startup.cs 中有以下内容:
services.AddSingleton<IAWSService, AWSService>();
services.AddAWSService<IAmazonS3>();
(我尝试将 AsScoped() 配置为无效。)
这是导致问题的功能:
public class AWSService : IAWSService
{
private readonly IAmazonS3 _s3Client;
public AWSService(IAmazonS3 s3Client)
{
_s3Client = s3Client;
}
public async Task<byte[]> ReadObjectFromS3Async(string bucketName, string keyName)
{
try
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = bucketName,
Key = keyName
};
using (_s3Client)
{
MemoryStream ms = new MemoryStream();
using (var getObjectResponse = await _s3Client.GetObjectAsync(request))
{
getObjectResponse.ResponseStream.CopyTo(ms);
}
var download = new FileContentResult(ms.ToArray(), "application/pdf");
return download.FileContents;
}
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
return null;
}
}
}
我第一次运行该函数时,断点显示 this.s3client 未释放,但随后尝试运行此函数显示 s3client 已释放,因此出现错误。
心有法竹
POPMUISE
侃侃无极
慕哥6287543
慕田峪9158850
随时随地看视频慕课网APP
相关分类