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. namespace S3bucketDemo.Helpers
  9. {
  10. public interface IAWSS3BucketHelper
  11. {
  12. Task<bool> UploadFile(System.IO.Stream inputStream, string fileName);
  13. Task<ListVersionsResponse> FilesList();
  14. Task<Stream> GetFile(string key);
  15. Task<bool> DeleteFile(string key);
  16. }
  17. public class AWSS3BucketHelper : IAWSS3BucketHelper
  18. {
  19. private readonly IAmazonS3 _amazonS3;
  20. private readonly ServiceConfiguration _settings;
  21. public AWSS3BucketHelper(IAmazonS3 s3Client, IOptions<ServiceConfiguration> settings)
  22. {
  23. this._amazonS3 = s3Client;
  24. this._settings = settings.Value;
  25. }
  26. public async Task<bool> UploadFile(System.IO.Stream inputStream, string fileName)
  27. {
  28. try
  29. {
  30. PutObjectRequest request = new PutObjectRequest()
  31. {
  32. InputStream = inputStream,
  33. BucketName = _settings.AWSS3.BucketName,
  34. Key = fileName
  35. };
  36. PutObjectResponse response = await _amazonS3.PutObjectAsync(request);
  37. if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
  38. return true;
  39. else
  40. return false;
  41. }
  42. catch (Exception ex)
  43. {
  44. throw ex;
  45. }
  46. }
  47. public async Task<ListVersionsResponse> FilesList()
  48. {
  49. return await _amazonS3.ListVersionsAsync(_settings.AWSS3.BucketName);
  50. }
  51. public async Task<Stream> GetFile(string key)
  52. {
  53. GetObjectResponse response = await _amazonS3.GetObjectAsync(_settings.AWSS3.BucketName, key);
  54. if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
  55. return response.ResponseStream;
  56. else
  57. return null;
  58. }
  59. public async Task<bool> DeleteFile(string key)
  60. {
  61. try
  62. {
  63. DeleteObjectResponse response = await _amazonS3.DeleteObjectAsync(_settings.AWSS3.BucketName, key);
  64. if (response.HttpStatusCode == System.Net.HttpStatusCode.NoContent)
  65. return true;
  66. else
  67. return false;
  68. }
  69. catch (Exception ex)
  70. {
  71. throw ex;
  72. }
  73. }
  74. }
  75. }
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. namespace S3bucketDemo.Services
  10. {
  11. public interface IAWSS3FileService
  12. {
  13. Task<bool> UploadFile(UploadFileName uploadFileName);
  14. Task<List<string>> FilesList();
  15. Task<Stream> GetFile(string key);
  16. Task<bool> UpdateFile(UploadFileName uploadFileName, string key);
  17. Task<bool> DeleteFile(string key);
  18. }
  19. public class AWSS3FileService : IAWSS3FileService
  20. {
  21. private readonly IAWSS3BucketHelper _AWSS3BucketHelper;
  22. public AWSS3FileService(IAWSS3BucketHelper AWSS3BucketHelper)
  23. {
  24. this._AWSS3BucketHelper = AWSS3BucketHelper;
  25. }
  26. public async Task<bool> UploadFile(UploadFileName uploadFileName)
  27. {
  28. try
  29. {
  30. var path = Path.Combine("Files", uploadFileName.ToString() + ".png");
  31. using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))
  32. {
  33. string fileExtension = Path.GetExtension(path);
  34. string fileName = string.Empty;
  35. fileName = $"{DateTime.Now.Ticks}{fileExtension}";
  36. return await _AWSS3BucketHelper.UploadFile(fsSource, fileName);
  37. }
  38. }
  39. catch (Exception ex)
  40. {
  41. throw ex;
  42. }
  43. }
  44. public async Task<List<string>> FilesList()
  45. {
  46. try
  47. {
  48. ListVersionsResponse listVersions = await _AWSS3BucketHelper.FilesList();
  49. return listVersions.Versions.Select(c => c.Key).ToList();
  50. }
  51. catch (Exception ex)
  52. {
  53. throw ex;
  54. }
  55. }
  56. public async Task<Stream> GetFile(string key)
  57. {
  58. try
  59. {
  60. Stream fileStream = await _AWSS3BucketHelper.GetFile(key);
  61. if (fileStream == null)
  62. {
  63. Exception ex = new Exception("File Not Found");
  64. throw ex;
  65. }
  66. else
  67. {
  68. return fileStream;
  69. }
  70. }
  71. catch (Exception ex)
  72. {
  73. throw ex;
  74. }
  75. }
  76. public async Task<bool> UpdateFile(UploadFileName uploadFileName, string key)
  77. {
  78. try
  79. {
  80. var path = Path.Combine("Files", uploadFileName.ToString() + ".png");
  81. using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))
  82. {
  83. return await _AWSS3BucketHelper.UploadFile(fsSource, key);
  84. }
  85. }
  86. catch (Exception ex)
  87. {
  88. throw ex;
  89. }
  90. }
  91. public async Task<bool> DeleteFile(string key)
  92. {
  93. try
  94. {
  95. return await _AWSS3BucketHelper.DeleteFile(key);
  96. }
  97. catch (Exception ex)
  98. {
  99. throw ex;
  100. }
  101. }
  102. }
  103. }
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. namespace S3bucketDemo
  12. {
  13. public class Startup
  14. {
  15. public Startup(IConfiguration configuration)
  16. {
  17. Configuration = configuration;
  18. }
  19. readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
  20. public IConfiguration Configuration { get; }
  21. // This method gets called by the runtime. Use this method to add services to the container.
  22. public void ConfigureServices(IServiceCollection services)
  23. {
  24. services.AddControllers();
  25. var appSettingsSection = Configuration.GetSection("ServiceConfiguration");
  26. services.AddAWSService<IAmazonS3>();
  27. services.Configure<ServiceConfiguration>(appSettingsSection);
  28. services.AddTransient<IAWSS3FileService, AWSS3FileService>();
  29. services.AddTransient<IAWSS3BucketHelper, AWSS3BucketHelper>();
  30. services.AddSwaggerGen(c =>
  31. {
  32. c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
  33. });
  34. services.AddCors(options =>
  35. {
  36. options.AddPolicy(name: MyAllowSpecificOrigins, builder =>
  37. builder
  38. .AllowAnyOrigin()
  39. .AllowAnyMethod()
  40. .AllowAnyHeader());
  41. // .AllowCredentials());
  42. });
  43. }
  44. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  45. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  46. {
  47. if (env.IsDevelopment())
  48. {
  49. app.UseDeveloperExceptionPage();
  50. }
  51. app.UseHttpsRedirection();
  52. app.UseRouting();
  53. app.UseAuthorization();
  54. app.UseCors(MyAllowSpecificOrigins);
  55. // Enable middleware to serve generated Swagger as a JSON endpoint.
  56. app.UseSwagger();
  57. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  58. // specifying the Swagger JSON endpoint.
  59. app.UseSwaggerUI(c =>
  60. {
  61. c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
  62. });
  63. app.UseEndpoints(endpoints =>
  64. {
  65. endpoints.MapControllers();
  66. });
  67. }
  68. }
  69. }
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. namespace S3bucketDemo.Controllers
  6. {
  7. [Produces("application/json")]
  8. [Route("api/[controller]")]
  9. [ApiController]
  10. public class AWSS3FileController : ControllerBase
  11. {
  12. private readonly IAWSS3FileService _AWSS3FileService;
  13. public AWSS3FileController(IAWSS3FileService AWSS3FileService)
  14. {
  15. this._AWSS3FileService = AWSS3FileService;
  16. }
  17. [Route("uploadFile")]
  18. [HttpPost]
  19. public async Task<IActionResult> UploadFileAsync(UploadFileName uploadFileName)
  20. {
  21. var result = await _AWSS3FileService.UploadFile(uploadFileName);
  22. return Ok(new { isSucess = result });
  23. }
  24. [Route("filesList")]
  25. [HttpGet]
  26. public async Task<IActionResult> FilesListAsync()
  27. {
  28. var result = await _AWSS3FileService.FilesList();
  29. return Ok(result);
  30. }
  31. [Route("getFile/{fileName}")]
  32. [HttpGet]
  33. public async Task<IActionResult> GetFile(string fileName)
  34. {
  35. try
  36. {
  37. var result = await _AWSS3FileService.GetFile(fileName);
  38. return File(result, "image/png");
  39. }
  40. catch
  41. {
  42. return Ok("NoFile");
  43. }
  44. }
  45. [Route("updateFile")]
  46. [HttpPut]
  47. public async Task<IActionResult> UpdateFile(UploadFileName uploadFileName, string fileName)
  48. {
  49. var result = await _AWSS3FileService.UpdateFile(uploadFileName, fileName);
  50. return Ok(new { isSucess = result });
  51. }
  52. [Route("deleteFile/{fileName}")]
  53. [HttpDelete]
  54. public async Task<IActionResult> DeleteFile(string fileName)
  55. {
  56. var result = await _AWSS3FileService.DeleteFile(fileName);
  57. return Ok(new { isSucess = result });
  58. }
  59. }
  60. }
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