How To Upload Any File On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project

Introduction

 
In this article, we will learn how to create S3 Bucket in AWS, how to upload files in S3 Bucket, how to read files from S3 Bucket, and how to delete the file from S3 Bucket in ASP.NET Core.
 
Prerequisites
  • Software
    • Dot NET Core
    • Visual Studio 2017 with last update or Visual Studio 2019
  • Skills
    • C#
    • AWS
Step 01 - Create Project
 
Open Visual Studio Click on “Create a new project”
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Select the ASP.NET Core Web Application option.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Add the Project name and Solution name.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Select “API” option with “.NET Core” and “ASP .NET Core 3.1” for create ASP .NET API.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Users can see the default folder structure.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step 02 - Install Nuget Packages
 
In this step, we need to install the following NuGet packages:
1. AWSSDK.Extensions.NETCore.Setup
2. AWSSDK.S3
3. Swashbuckle.AspNetCore
4. Swashbuckle.AspNetCore.Annotations
Now, we'll proceed to install the above package from Nuget, right-click on the S3bucketDemo project:
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Change to the “Browse” tab and type AWSSDK.Extensions.NETCore.Setup:
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Next...
 
Install AWSSDK.S3 package
Install Microsoft.IdentityModel.Tokens package
Install Swashbuckle.AspNetCore package
Install Swashbuckle.AspNetCore.Annotations package
 
Step 03 - Now, we have to Install and Configure AWS CLI in our Windows computer
 
Step A
 
Go to https://aws.amazon.com/cli/ site and click on “Download and run the 64-bit Windows installer” link as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step B
 
After successfully download “AWSCLIV2.msi” file, then install.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step C
 
Check that “AWSCLIV2” installed properly, then open CMD run as an administrator.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step D
 
Execute command “aws --v” to check if “AWSCLIV2” installed properly or not.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step E
 
Now login in to https://aws.amazon.com/.
 
Step F
 
Search IAM in the “Find Services” textbox, as per the below screenshot:
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step G
 
Click on the “Users” link and click on a particular user, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step H
 
Then click on the “Security credentials” link, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step I
 
Then click on the “Create access key” link, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step J
 
Then copy “Access key ID”, “Secret access key” and Download .csv for feature use, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project 
 
Step K
 
Now, come back to CMD and run “aws configure” command as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project 
  1. $ aws configure  
  2. AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE  
  3. AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY  
  4. Default region name [None]: us-west-2  
  5. Default output format [None]: json  
Reference Link - https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html 
 
Step L
 
Open “File Explorer” and go to your user name folder like “C:\Users\UserName” and open the “.aws” folder, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
Step 04: Now, we have to create S3 on AWS.
 
Step A
 
Go to the AWS dashboard and Search s3 in the “Find Services” textbox, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step B
 
Click on the “Create bucket” button, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step C
 
Add “Bucket name” in the “Name and region” tab, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step D
 
Enable/Disable Configure as per requirement in the “Configure options” tab.

How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step E
 
Set permission as per requirement in the “Set permissions” tab.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step F
 
Then review your bucket configuration in the “Review” tab and click on Create bucket.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step G
 
Then copy your bucket name.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step 05 - Now we Create Models.
 
Now, create a directory with the name Models and add the following files:
 
ServiceConfiguration.cs
 
EnumModel.cs
 
Code for ServiceConfiguration.cs file:
  1. namespace S3bucketDemo.Models  
  2. {  
  3.     public class ServiceConfiguration  
  4.     {  
  5.         public AWSS3Configuration AWSS3 { get; set; }  
  6.     }  
  7.     public class AWSS3Configuration  
  8.     {  
  9.         public string BucketName { get; set; }  
  10.     }  
  11. }  
Code for EnumModel.cs file:
  1. namespace S3bucketDemo.Models  
  2. {  
  3.     public enum UploadFileName  
  4.     {  
  5.         First = 1,  
  6.         Second = 2,  
  7.         Third = 3,  
  8.         Fourth = 4,  
  9.         Fifth = 5,  
  10.     }  
  11. }  
Step 06 – Update appsettings.Development.json
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Code for appsettings.Development.json file:
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "ServiceConfiguration": {  
  10.     "AWSS3": {  
  11.       "BucketName""*BUCKET_NAME*"  
  12.     }  
  13.   }  
  14. }  
Replace *BUCKET_NAME* with your Bucket Name
 
Step 07 – Create Helpers
 
Now, create a directory with the name Helpers and add the following files.
 
AWSS3BucketHelper.cs:
  1. using Amazon.S3;  
  2. using Amazon.S3.Model;  
  3. using Microsoft.Extensions.Options;  
  4. using S3bucketDemo.Models;  
  5. using System;  
  6. using System.IO;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace S3bucketDemo.Helpers  
  10. {  
  11.     public interface IAWSS3BucketHelper  
  12.     {  
  13.         Task<bool> UploadFile(System.IO.Stream inputStream, string fileName);  
  14.         Task<ListVersionsResponse> FilesList();  
  15.         Task<Stream> GetFile(string key);  
  16.         Task<bool> DeleteFile(string key);  
  17.     }  
  18.     public class AWSS3BucketHelper : IAWSS3BucketHelper  
  19.     {  
  20.         private readonly IAmazonS3 _amazonS3;  
  21.         private readonly ServiceConfiguration _settings;  
  22.         public AWSS3BucketHelper(IAmazonS3 s3Client, IOptions<ServiceConfiguration> settings)  
  23.         {  
  24.             this._amazonS3 = s3Client;  
  25.             this._settings = settings.Value;  
  26.         }  
  27.         public async Task<bool> UploadFile(System.IO.Stream inputStream, string fileName)  
  28.         {  
  29.             try  
  30.             {  
  31.                 PutObjectRequest request = new PutObjectRequest()  
  32.                 {  
  33.                     InputStream = inputStream,  
  34.                     BucketName = _settings.AWSS3.BucketName,  
  35.                     Key = fileName  
  36.                 };  
  37.                 PutObjectResponse response = await _amazonS3.PutObjectAsync(request);  
  38.                 if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)  
  39.                     return true;  
  40.                 else  
  41.                     return false;  
  42.             }  
  43.             catch (Exception ex)  
  44.             {  
  45.   
  46.                 throw ex;  
  47.             }  
  48.         }  
  49.         public async Task<ListVersionsResponse> FilesList()  
  50.         {  
  51.             return await _amazonS3.ListVersionsAsync(_settings.AWSS3.BucketName);  
  52.         }  
  53.         public async Task<Stream> GetFile(string key)  
  54.         {  
  55.   
  56.             GetObjectResponse response = await _amazonS3.GetObjectAsync(_settings.AWSS3.BucketName, key);  
  57.             if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)  
  58.                 return response.ResponseStream;  
  59.             else  
  60.                 return null;  
  61.         }  
  62.   
  63.         public async Task<bool> DeleteFile(string key)  
  64.         {  
  65.             try  
  66.             {  
  67.                 DeleteObjectResponse response = await _amazonS3.DeleteObjectAsync(_settings.AWSS3.BucketName, key);  
  68.                 if (response.HttpStatusCode == System.Net.HttpStatusCode.NoContent)  
  69.                     return true;  
  70.                 else  
  71.                     return false;  
  72.             }  
  73.             catch (Exception ex)  
  74.             {  
  75.                 throw ex;  
  76.             }  
  77.   
  78.   
  79.         }  
  80.     }  
  81. }  
Step 08 – Create Service
 
Now, create a directory with the name Services and add the following files:
 
AWSS3FileService.cs
  1. using Amazon.S3.Model;  
  2. using S3bucketDemo.Helpers;  
  3. using S3bucketDemo.Models;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace S3bucketDemo.Services  
  11. {  
  12.     public interface IAWSS3FileService  
  13.     {  
  14.         Task<bool> UploadFile(UploadFileName uploadFileName);  
  15.         Task<List<string>> FilesList();  
  16.         Task<Stream> GetFile(string key);  
  17.         Task<bool> UpdateFile(UploadFileName uploadFileName, string key);  
  18.         Task<bool> DeleteFile(string key);  
  19.     }  
  20.     public class AWSS3FileService : IAWSS3FileService  
  21.     {  
  22.         private readonly IAWSS3BucketHelper _AWSS3BucketHelper;  
  23.   
  24.         public AWSS3FileService(IAWSS3BucketHelper AWSS3BucketHelper)  
  25.         {  
  26.             this._AWSS3BucketHelper = AWSS3BucketHelper;  
  27.         }  
  28.         public async Task<bool> UploadFile(UploadFileName uploadFileName)  
  29.         {  
  30.             try  
  31.             {  
  32.                 var path = Path.Combine("Files", uploadFileName.ToString() + ".png");  
  33.                 using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))  
  34.                 {  
  35.                     string fileExtension = Path.GetExtension(path);  
  36.                     string fileName = string.Empty;  
  37.                     fileName = $"{DateTime.Now.Ticks}{fileExtension}";  
  38.                     return await _AWSS3BucketHelper.UploadFile(fsSource, fileName);  
  39.                 }  
  40.             }  
  41.             catch (Exception ex)  
  42.             {  
  43.                 throw ex;  
  44.             }  
  45.         }  
  46.         public async Task<List<string>> FilesList()  
  47.         {  
  48.             try  
  49.             {  
  50.                 ListVersionsResponse listVersions = await _AWSS3BucketHelper.FilesList();  
  51.                 return listVersions.Versions.Select(c => c.Key).ToList();  
  52.             }  
  53.             catch (Exception ex)  
  54.             {  
  55.   
  56.                 throw ex;  
  57.             }  
  58.         }  
  59.         public async Task<Stream> GetFile(string key)  
  60.         {  
  61.             try  
  62.             {  
  63.                 Stream fileStream = await _AWSS3BucketHelper.GetFile(key);  
  64.                 if (fileStream == null)  
  65.                 {  
  66.                     Exception ex = new Exception("File Not Found");  
  67.                     throw ex;  
  68.                 }  
  69.                 else  
  70.                 {  
  71.                     return fileStream;  
  72.                 }  
  73.             }  
  74.             catch (Exception ex)  
  75.             {  
  76.                 throw ex;  
  77.             }  
  78.         }  
  79.         public async Task<bool> UpdateFile(UploadFileName uploadFileName, string key)  
  80.         {  
  81.             try  
  82.             {  
  83.                 var path = Path.Combine("Files", uploadFileName.ToString() + ".png");  
  84.                 using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))  
  85.                 {  
  86.                     return await _AWSS3BucketHelper.UploadFile(fsSource, key);  
  87.                 }  
  88.             }  
  89.             catch (Exception ex)  
  90.             {  
  91.                 throw ex;  
  92.             }  
  93.         }  
  94.         public async Task<bool> DeleteFile(string key)  
  95.         {  
  96.             try  
  97.             {  
  98.                 return await _AWSS3BucketHelper.DeleteFile(key);  
  99.             }  
  100.             catch (Exception ex)  
  101.             {  
  102.                 throw ex;  
  103.             }  
  104.         }  
  105.     }  
  106. }  
Step 09 – Create Files Folder
 
Now, create a directory with the name Files and add random any five “.png” image with “First.png”, “Second.png”, “Third.png”, “Fourth.png” and “Fifth.png” as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Step 10 – Update Startup.cs
 
Code for Startup.cs file:
  1. using Amazon.S3;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.Extensions.Configuration;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. using Microsoft.Extensions.Hosting;  
  7. using Microsoft.OpenApi.Models;  
  8. using S3bucketDemo.Helpers;  
  9. using S3bucketDemo.Models;  
  10. using S3bucketDemo.Services;  
  11.   
  12. namespace S3bucketDemo  
  13. {  
  14.     public class Startup  
  15.     {  
  16.         public Startup(IConfiguration configuration)  
  17.         {  
  18.             Configuration = configuration;  
  19.         }  
  20.         readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";  
  21.         public IConfiguration Configuration { get; }  
  22.   
  23.         // This method gets called by the runtime. Use this method to add services to the container.  
  24.         public void ConfigureServices(IServiceCollection services)  
  25.         {  
  26.             services.AddControllers();  
  27.             var appSettingsSection = Configuration.GetSection("ServiceConfiguration");  
  28.             services.AddAWSService<IAmazonS3>();  
  29.             services.Configure<ServiceConfiguration>(appSettingsSection);  
  30.             services.AddTransient<IAWSS3FileService, AWSS3FileService>();  
  31.             services.AddTransient<IAWSS3BucketHelper, AWSS3BucketHelper>();  
  32.             services.AddSwaggerGen(c =>  
  33.             {  
  34.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "My API", Version = "v1" });  
  35.             });  
  36.             services.AddCors(options =>  
  37.             {  
  38.                 options.AddPolicy(name: MyAllowSpecificOrigins, builder =>  
  39.                 builder  
  40.                 .AllowAnyOrigin()  
  41.                 .AllowAnyMethod()  
  42.                 .AllowAnyHeader());  
  43.                 // .AllowCredentials());  
  44.             });  
  45.         }  
  46.   
  47.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  48.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  49.         {  
  50.             if (env.IsDevelopment())  
  51.             {  
  52.                 app.UseDeveloperExceptionPage();  
  53.             }  
  54.             app.UseHttpsRedirection();  
  55.             app.UseRouting();  
  56.             app.UseAuthorization();  
  57.             app.UseCors(MyAllowSpecificOrigins);  
  58.             // Enable middleware to serve generated Swagger as a JSON endpoint.  
  59.             app.UseSwagger();  
  60.             // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),  
  61.             // specifying the Swagger JSON endpoint.  
  62.             app.UseSwaggerUI(c =>  
  63.             {  
  64.                 c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");  
  65.             });  
  66.   
  67.             app.UseEndpoints(endpoints =>  
  68.             {  
  69.                 endpoints.MapControllers();  
  70.             });  
  71.         }  
  72.     }  
  73. }  
Step 11 – Add Controller
 
Now, add the AWSS3FileController.cs files in the Controllers folder:
 
Code for AuthController.cs file:
  1. using Microsoft.AspNetCore.Mvc;  
  2. using S3bucketDemo.Models;  
  3. using S3bucketDemo.Services;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace S3bucketDemo.Controllers  
  7. {  
  8.     [Produces("application/json")]  
  9.     [Route("api/[controller]")]  
  10.     [ApiController]  
  11.     public class AWSS3FileController : ControllerBase  
  12.     {  
  13.         private readonly IAWSS3FileService _AWSS3FileService;  
  14.         public AWSS3FileController(IAWSS3FileService AWSS3FileService)  
  15.         {  
  16.             this._AWSS3FileService = AWSS3FileService;  
  17.         }  
  18.         [Route("uploadFile")]  
  19.         [HttpPost]  
  20.         public async Task<IActionResult> UploadFileAsync(UploadFileName uploadFileName)  
  21.         {  
  22.             var result = await _AWSS3FileService.UploadFile(uploadFileName);  
  23.             return Ok(new { isSucess = result });  
  24.         }  
  25.         [Route("filesList")]  
  26.         [HttpGet]  
  27.         public async Task<IActionResult> FilesListAsync()  
  28.         {  
  29.             var result = await _AWSS3FileService.FilesList();  
  30.             return Ok(result);  
  31.         }  
  32.         [Route("getFile/{fileName}")]  
  33.         [HttpGet]  
  34.         public async Task<IActionResult> GetFile(string fileName)  
  35.         {  
  36.             try  
  37.             {  
  38.                 var result = await _AWSS3FileService.GetFile(fileName);  
  39.                 return File(result, "image/png");  
  40.             }  
  41.             catch  
  42.             {  
  43.                 return Ok("NoFile");  
  44.             }  
  45.   
  46.         }  
  47.         [Route("updateFile")]  
  48.         [HttpPut]  
  49.         public async Task<IActionResult> UpdateFile(UploadFileName uploadFileName, string fileName)  
  50.         {  
  51.             var result = await _AWSS3FileService.UpdateFile(uploadFileName, fileName);  
  52.             return Ok(new { isSucess = result });  
  53.         }  
  54.         [Route("deleteFile/{fileName}")]  
  55.         [HttpDelete]  
  56.         public async Task<IActionResult> DeleteFile(string fileName)  
  57.         {  
  58.             var result = await _AWSS3FileService.DeleteFile(fileName);  
  59.             return Ok(new { isSucess = result });  
  60.         }  
  61.     }  
  62. }  
Step 12 - Running Web API
 
Now, press F5 to start debugging for the Web API project, if everything is OK, we'll get the following output in the browser.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
Now we have to open “/Swagger” to execute the API for upload and read file from the “Files” folder in our solution.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Upload File in AWS S3Bucket
 
Click on the “/api/AWSS3File/uploadFile” tab and click on the “Try it out” button, as shown in the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Now select any number in the dropdown and click on the “Execute” button then you can see the API response, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
List of Files name in AWS S3Bucket
 
Click on “/api/AWSS3File/filesList” tab and click on “Try it out” then click on the “Execute” button, then you can see the API response, as per the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Read a file from AWS S3Bucket
 
Copy any file name from “/api/AWSS3File/filesList” response and click on “/api/AWSS3File/getFile/{fileName}” tab and click on “Try it out” then past the file name in the text box then click on the “Execute” button then you can see API response, as per below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Update File in AWS S3Bucket
 
Copy any file name from “/api/AWSS3File/filesList” response and click on “/api/AWSS3File/updateFile” tab and click on “Try it out” then past the file name in the text box then select any number in the dropdown and click on “Execute” button then you can see the API response, as shown in the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project
 
Delete File from AWS S3Bucket
 
Copy any file name from “/api/AWSS3File/filesList” response and click on “/api/AWSS3File/deleteFile/{fileName}” tab and click on “Try it out” then past the file name in the text box then click on the “Execute” button, then you can see API response as shown in the below screenshot.
 
How To Upload Any Files On Amazon Simple Storage Service (AWS S3) In ASP.NET Core Project