编程语言
首页 > 编程语言> > c#-在.NET Core中配置AWS S3客户端

c#-在.NET Core中配置AWS S3客户端

作者:互联网

我正在遵循有关在.NET Core中配置AWS开发工具包以将文件上传到S3存储桶的this指南.

我的app.settings.json文件包含以下内容:

{
  "AWS": {
    "Region": "us-west-1",
    "AccessKey": "access_key",
    "SecretKey": "secret_key"
  }
  ...
}

这是我的StartUp类:

public class Startup
{
    public IContainer ApplicationContainer { get; private set; }
    public IConfiguration Configuration { get; }

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();
        services.AddMvc();
        services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
        services.AddAWSService<IAmazonS3>();
    }
}

我相信这意味着我可以将客户端对象注入将使用app.settings值的类中.我正在尝试注入对象,并像这样进行S3调用:

public class FileUploader
{
    private readonly IAmazonS3 client;

    public FileUploader(IAmazonS3 client)
    {
        this.client = client;
    }

    public async Task Upload()
    {
        var request = new PutObjectRequest
        {
            BucketName = "bucketName",
            Key = "Test",
            FilePath = "test_file.txt",
            ContentType = "text/plain"
        };

        var cancellationToken = new CancellationToken();
        var response = await client.PutObjectAsync(request, cancellationToken);
    }
}

当前,当我尝试执行此操作时,该应用程序在尝试注入S3Client时挂起.最初,我并不是要注入S3Client,而是要在我的FileUploaded类中实例化它.那时候我遇到了一个错误,因为我没有指定AccessKey等,也找不到设置它的方法.

我究竟做错了什么?

解决方法:

看来我应该只在我的应用程序设置中包括地区和个人资料.该配置文件应使用信息here生成.

标签:amazon-web-services,amazon-s3,aws-sdk,c
来源: https://codeday.me/bug/20191110/2015533.html