Monday, October 30, 2017

Configuring AWS S3 Client in .NET Core

Leave a Comment

I'm following this guide on configuring the AWS SDK in .NET Core to upload a file to an S3 bucket.

My app.settings.json file contains this:

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

Here is my StartUp class:

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>();     } } 

I believe this means I can just inject a client object into a class which will use the app.settings values. I'm trying to inject the object and make an S3 call like this:

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);     } } 

Currently, when I attempt to do this, the app hangs when it tries to inject the S3Client. Originally, I wasn't trying to inject the S3Client, but rather instantiate it within my FileUploaded class. I was getting an error then because I wasn't specifying the AccessKey, etc. and I couldn't find a way to set that up.

What am I doing wrong?

1 Answers

Answers 1

It looks like I should have been including only Region and Profile in my appsettings. The profile should be generated using information here.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment