Read Files from an AWS S3 Bucket in ASP.NET Core
Amazon S3 is a popular place to keep files such as master data sheets, reports and uploads. In this tutorial we build a small ASP.NET Core MVC application that connects to an S3 bucket, reads an Excel file of public holidays, shows the rows on a page and, with one more click, imports them into a SQL Server table with Entity Framework Core.
The project is called HolidayImportApp and runs on .NET 10. Every output on this page, including the screenshot, comes from a real run of the application.
Note: the bucket name, file name and server name in the configuration below are example values. Use your own, and never publish your real AWS keys.
How the application works
- The user opens the Holiday page and clicks Read Excel from S3.
- The application downloads the Excel file from S3 with the AWS SDK for .NET and reads it with ClosedXML.
- The rows are shown in a table, together with an Import into SQL Server button.
- Clicking Import reads the file again and saves the rows in the
tblHolidaytable with EF Core.
The files we will write:
HolidayImportApp/
├── appsettings.json # AWS region, bucket, file name, connection string
├── Program.cs # registers EF Core, the S3 client and the service
├── Models/Holiday.cs # the tblHoliday table
├── Data/ApplicationDbContext.cs # EF Core DbContext
├── ViewModels/HolidayImportViewModel.cs
├── Services/IHolidayService.cs
├── Services/HolidayService.cs # reads S3 + imports into SQL Server
├── Controllers/HolidayController.cs
└── Views/Holiday/Index.cshtml
How an ASP.NET Core application connects to AWS
Before writing code, it helps to understand what "connecting to AWS" means. There is no permanent connection like a database connection. Every call, such as "give me this file", is a separate HTTPS request to the S3 service. The AWS SDK does three things for us:
- It finds the credentials (an access key ID and secret access key, or a role).
- It sends the request to the right region, for example
https://s3.ap-south-1.amazonaws.com. - It signs every request with the secret key, so AWS knows who is calling. The secret key itself is never sent.
When we create an AmazonS3Client without passing keys, the SDK searches for credentials in a fixed order, called the credential chain:
- Environment variables
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - The shared credentials file
C:\Users\<your user>\.aws\credentials, written byaws configure(profiledefault, or the one named inAWS_PROFILE). - On Windows, the AWS SDK Store, used by the AWS Toolkit for Visual Studio.
- When the app runs on AWS (EC2, ECS, Lambda, Elastic Beanstalk), the IAM role of that machine or container.
This is why our code and appsettings.json contain no access keys. On your laptop the keys come from aws configure; on an AWS server they come from an IAM role. The same code works in both places.
Step 1: Prepare AWS (IAM user and aws configure)
- In the AWS Console, create an S3 bucket and upload the Excel file, for example into a folder
Master-Files/Holidays/. - Open IAM > Users > Create user and attach a policy that allows reading the bucket (the policy is shown below).
- Open the user, choose Security credentials > Create access key > Command Line Interface (CLI), and copy both keys.
- Install the AWS CLI v2 and run
aws configurewith those keys and the region of your bucket.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:ListBucket"],
"Resource": [
"arn:aws:s3:::my-company-master-files",
"arn:aws:s3:::my-company-master-files/*"
]
}
]
}
aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: ap-south-1
Default output format [None]: json
The keys above are AWS's documented example values. Each of these steps is explained in more detail in reading Excel from S3 in Python; the AWS side is exactly the same for .NET.
Step 2: Create the project and install the NuGet packages
Create an ASP.NET Core Web App (Model-View-Controller) project named HolidayImportApp on .NET 10, then install these packages:
dotnet add package AWSSDK.S3
dotnet add package ClosedXML
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
| Package | Version used | Why we need it |
|---|---|---|
AWSSDK.S3 | 4.1.3.1 | The official AWS SDK for S3. Gives us AmazonS3Client, GetObjectRequest and GetObjectAsync. It pulls in AWSSDK.Core, which handles credentials, regions and request signing. |
ClosedXML | 0.105.1 | Reads and writes .xlsx files without Microsoft Office. Free (MIT licence). |
Microsoft.EntityFrameworkCore.SqlServer | 10.0.0 | EF Core provider for SQL Server, used to save the holidays. |
Microsoft.EntityFrameworkCore.Tools | 10.0.0 | Optional: migration commands such as Add-Migration in Visual Studio. |
The resulting HolidayImportApp.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" Version="4.1.3.1" />
<PackageReference Include="ClosedXML" Version="0.105.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>
Step 3: Create the SQL Server table
Run this script in SSMS. It is the exact script EF Core generates for the Holiday model in Step 5 (we printed it with Database.GenerateCreateScript()), so the table and the model match:
CREATE DATABASE HolidayDB;
GO
USE HolidayDB;
GO
CREATE TABLE [tblHoliday] (
[HolidayId] int NOT NULL IDENTITY,
[HolidayName] nvarchar(50) NOT NULL,
[Description] nvarchar(500) NOT NULL,
[HolidayTypeId] int NOT NULL,
CONSTRAINT [PK_tblHoliday] PRIMARY KEY ([HolidayId])
);
GO
HolidayId is an IDENTITY column: SQL Server numbers the rows itself (1, 2, 3, ...), so we do not insert it from Excel.
Step 4: Add the settings to appsettings.json
The region, bucket and file name are not hard-coded in C#. They live in appsettings.json, so they can be different in development and production:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=localhost\\SQLEXPRESS;Database=HolidayDB;Trusted_Connection=True;TrustServerCertificate=True"
},
"AWS": {
"Region": "ap-south-1",
"BucketName": "my-company-master-files",
"FileName": "Master-Files/Holidays/India_Holidays.xlsx"
}
}
- Region: the region code where the bucket was created, as shown next to the bucket in the S3 console.
- BucketName: only the bucket name, without
s3://. - FileName: the object key, the full path of the file inside the bucket, including folders. Keys are case-sensitive.
Important: do not put AccessKey or SecretKey values in appsettings.json. This file is committed to Git and copied to the server when you publish. Let the SDK find the keys through the credential chain instead. If you really need keys outside AWS, use environment variables or User Secrets (dotnet user-secrets) during development.
Step 5: The model, DbContext and ViewModel
Models/Holiday.cs maps to the tblHoliday table. The [Table] attribute is needed because the table name differs from the class name. EF Core treats HolidayId as the primary key by convention (class name + Id).
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace HolidayImportApp.Models
{
[Table("tblHoliday")]
public class Holiday
{
public int HolidayId { get; set; }
[Required]
[StringLength(50)]
public string HolidayName { get; set; } = string.Empty;
[Required]
[StringLength(500)]
public string Description { get; set; } = string.Empty;
[Required]
public int HolidayTypeId { get; set; }
}
}
Data/ApplicationDbContext.cs:
using HolidayImportApp.Models;
using Microsoft.EntityFrameworkCore;
namespace HolidayImportApp.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Holiday> Holidays { get; set; }
}
}
ViewModels/HolidayImportViewModel.cs. HolidayExcelRow holds one row exactly as it is in Excel; HolidayImportViewModel is what the view receives:
namespace HolidayImportApp.ViewModels
{
public class HolidayExcelRow
{
public int HolidayId { get; set; }
public string HolidayName { get; set; } = "";
public string Description { get; set; } = "";
public int HolidayTypeId { get; set; }
}
public class HolidayImportViewModel
{
public List<HolidayExcelRow> Holidays { get; set; }
= new List<HolidayExcelRow>();
public string Message { get; set; } = "";
}
}
Keeping the Excel row separate from the database entity is a good habit: the Excel file has its own HolidayId column, but the database creates its own id.
Step 6: Configure Program.cs
Program.cs needs three registrations: the DbContext, the S3 client and our service.
using Amazon;
using Amazon.S3;
using HolidayImportApp.Data;
using HolidayImportApp.Services;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
)
);
// AWS S3 CONNECTION
builder.Services.AddSingleton<IAmazonS3>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
string region = configuration["AWS:Region"]!;
return new AmazonS3Client(
RegionEndpoint.GetBySystemName(region)
);
});
// REGISTER HOLIDAY SERVICE
builder.Services.AddScoped<IHolidayService, HolidayService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Holiday}/{action=Index}/{id?}")
.WithStaticAssets();
app.Run();
What the AWS part does:
- AddSingleton<IAmazonS3>(...): registers the S3 client in dependency injection, so any class can ask for
IAmazonS3in its constructor. Asking for the interface instead of the class also makes the service easy to test with a fake S3 client. - Singleton: one client for the whole application.
AmazonS3Clientis thread-safe and reuses its HTTP connections, so creating a new client per request would only waste resources. - configuration["AWS:Region"]: the colon reads a nested value: the
Regioninside theAWSsection of appsettings.json. - RegionEndpoint.GetBySystemName("ap-south-1"): turns the text into the region object the SDK needs.
- new AmazonS3Client(region): no keys are passed, so the SDK uses the credential chain described above.
The default route is changed to {controller=Holiday}, so the Holiday page opens at the root URL.
Alternative: the package AWSSDK.Extensions.NETCore.Setup can do the same registration with builder.Services.AddDefaultAWSOptions(builder.Configuration.GetAWSOptions()); and builder.Services.AddAWSService<IAmazonS3>();, reading the region (and an optional profile name) from the AWS section. The manual registration above needs no extra package and shows clearly what happens.
Step 7: The service that reads S3 and imports the data
Services/IHolidayService.cs:
using HolidayImportApp.ViewModels;
namespace HolidayImportApp.Services
{
public interface IHolidayService
{
Task<List<HolidayExcelRow>> ReadExcelFromS3Async();
Task<int> ImportHolidaysAsync();
}
}
Services/HolidayService.cs:
using Amazon.S3;
using Amazon.S3.Model;
using ClosedXML.Excel;
using HolidayImportApp.Data;
using HolidayImportApp.Models;
using HolidayImportApp.ViewModels;
using Microsoft.EntityFrameworkCore;
namespace HolidayImportApp.Services
{
public class HolidayService : IHolidayService
{
private readonly IAmazonS3 _s3Client;
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
public HolidayService(
IAmazonS3 s3Client,
ApplicationDbContext context,
IConfiguration configuration)
{
_s3Client = s3Client;
_context = context;
_configuration = configuration;
}
// STEP 1: READ EXCEL FROM S3
public async Task<List<HolidayExcelRow>> ReadExcelFromS3Async()
{
string bucketName = _configuration["AWS:BucketName"]!;
string fileName = _configuration["AWS:FileName"]!;
var request = new GetObjectRequest
{
BucketName = bucketName,
Key = fileName
};
using var response = await _s3Client.GetObjectAsync(request);
using var workbook = new XLWorkbook(response.ResponseStream);
var worksheet = workbook.Worksheet(1);
var holidays = new List<HolidayExcelRow>();
// Start from row 2 because row 1 contains headers
int lastRow = worksheet.LastRowUsed()?.RowNumber() ?? 1;
for (int row = 2; row <= lastRow; row++)
{
if (worksheet.Cell(row, 1).IsEmpty())
continue;
var holiday = new HolidayExcelRow
{
HolidayId = worksheet.Cell(row, 1).GetValue<int>(),
HolidayName = worksheet.Cell(row, 2).GetString(),
Description = worksheet.Cell(row, 3).GetString(),
HolidayTypeId = worksheet.Cell(row, 4).GetValue<int>()
};
holidays.Add(holiday);
}
return holidays;
}
// STEP 2: INSERT RECORDS INTO SQL SERVER
public async Task<int> ImportHolidaysAsync()
{
// Read Excel again from S3
var excelRecords = await ReadExcelFromS3Async();
int insertedCount = 0;
foreach (var item in excelRecords)
{
// Avoid importing the same holiday again
//bool alreadyExists = await _context.Holidays
// .AnyAsync(x =>
// x.HolidayName == item.HolidayName &&
// x.HolidayTypeId == item.HolidayTypeId);
//if (alreadyExists)
// continue;
var holiday = new Holiday
{
// HolidayId is generated by SQL Server
HolidayName = item.HolidayName,
Description = item.Description,
HolidayTypeId = item.HolidayTypeId
};
_context.Holidays.Add(holiday);
insertedCount++;
}
await _context.SaveChangesAsync();
return insertedCount;
}
}
}
Reading the file from S3, line by line
- Constructor injection: the service receives the singleton
IAmazonS3, theApplicationDbContextandIConfigurationfrom dependency injection. It never creates them itself. - GetObjectRequest: describes which object we want: the bucket and the key, both read from appsettings.json.
- GetObjectAsync: this is the moment the SDK finds the credentials, signs the request and calls S3. If the keys, permissions or file name are wrong, the exception is thrown here.
- using var response:
GetObjectResponseholds an open network stream, so it must be disposed.using vardisposes it at the end of the method. - new XLWorkbook(response.ResponseStream): ClosedXML opens the workbook directly from the S3 stream. Nothing is written to disk.
- Worksheet(1): the first sheet (ClosedXML counts from 1). LastRowUsed() finds the last row with data;
?? 1handles an empty sheet. - The loop starts at row 2 because row 1 contains the column headers. Empty rows are skipped.
- GetValue<int>() converts a cell to a number; GetString() returns the cell text.
Importing into SQL Server
ImportHolidaysAsyncreads the file from S3 again instead of trusting data posted back from the browser, so the import always uses the current file.- Each Excel row becomes a
Holidayentity.HolidayIdis not set, because SQL Server generates it. _context.Holidays.Addonly tracks the entities in memory. SaveChangesAsync() sends all of them to SQL Server in one batch and one transaction: either all 12 rows are saved or none.
Note that the duplicate check is commented out. We will see what that means in the output, and fix it.
Step 8: The controller
using HolidayImportApp.Services;
using HolidayImportApp.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace HolidayImportApp.Controllers
{
public class HolidayController : Controller
{
private readonly IHolidayService _holidayService;
public HolidayController(IHolidayService holidayService)
{
_holidayService = holidayService;
}
// DISPLAY PAGE
public IActionResult Index()
{
return View(new HolidayImportViewModel());
}
// READ EXCEL FROM S3
[HttpPost]
public async Task<IActionResult> Preview()
{
try
{
var holidays = await _holidayService.ReadExcelFromS3Async();
var model = new HolidayImportViewModel
{
Holidays = holidays,
Message = "Excel file read successfully from AWS S3."
};
return View("Index", model);
}
catch (Exception ex)
{
var model = new HolidayImportViewModel
{
Message = "Error reading Excel: " + ex.Message
};
return View("Index", model);
}
}
// INSERT RECORDS INTO SQL SERVER
[HttpPost]
public async Task<IActionResult> Import()
{
try
{
int count = await _holidayService.ImportHolidaysAsync();
TempData["Message"] = count + " holiday records imported successfully.";
return RedirectToAction("Index");
}
catch (Exception ex)
{
TempData["Message"] = "Import failed: " + ex.Message;
return RedirectToAction("Index");
}
}
}
}
- Preview returns the
Indexview directly with the rows, so they can be shown on the same page. - Import follows the Post/Redirect/Get pattern: after saving, it redirects to
Index. Refreshing the browser then repeats the harmless GET, not the import. The message survives the redirect in TempData. - Both actions catch exceptions and show the message on the page instead of an error screen.
Step 9: The view
Views/Holiday/Index.cshtml:
@model HolidayImportApp.ViewModels.HolidayImportViewModel
@{
ViewData["Title"] = "Holiday Excel Import";
}
<div class="container mt-4">
<h2>Holiday Excel Import from AWS S3</h2>
<hr />
@if (TempData["Message"] != null)
{
<div class="alert alert-info">@TempData["Message"]</div>
}
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="alert alert-success">@Model.Message</div>
}
<!-- READ EXCEL BUTTON -->
<form asp-controller="Holiday" asp-action="Preview" method="post">
<button type="submit" class="btn btn-primary">Read Excel from S3</button>
</form>
<br />
@if (Model.Holidays.Any())
{
<h4>Excel Records</h4>
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>Holiday ID</th>
<th>Holiday Name</th>
<th>Description</th>
<th>Holiday Type ID</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Holidays)
{
<tr>
<td>@item.HolidayId</td>
<td>@item.HolidayName</td>
<td>@item.Description</td>
<td>@item.HolidayTypeId</td>
</tr>
}
</tbody>
</table>
<h5>Total Records: @Model.Holidays.Count</h5>
<!-- IMPORT BUTTON -->
<form asp-controller="Holiday" asp-action="Import" method="post">
<button type="submit" class="btn btn-success">Import into SQL Server</button>
</form>
}
</div>
The import button is shown only after the file has been read, so the user always sees the data before importing it. The asp-action tag helpers build the form URLs /Holiday/Preview and /Holiday/Import.
Step 10: Run the application
Press F5 (or run dotnet run), and click Read Excel from S3. The application downloads the file from the bucket and shows all its rows:
The Holiday IDs 25 to 36 are the values from the Excel file. Now click Import into SQL Server:
EF Core logs the SQL it sends. All 12 rows are inserted with one MERGE statement, and OUTPUT INSERTED.[HolidayId] returns the new identity values to EF Core:
Check the table in SSMS:
SELECT * FROM tblHoliday ORDER BY HolidayId;
The data is the same as in Excel, but HolidayId now runs from 1 to 12, because the identity column generated new ids.
Importing twice: why the duplicate check matters
Click Import into SQL Server a second time. The page again says "12 holiday records imported successfully.", and the table now has duplicates:
SELECT COUNT(*) AS TotalRows, COUNT(DISTINCT HolidayName) AS DistinctNames FROM tblHoliday;
Row 13 is "Republic Day" again. Because HolidayId is generated by SQL Server, the primary key cannot detect the duplicate. The fix is the check that was commented out: before adding a holiday, ask the database whether it already exists.
foreach (var item in excelRecords)
{
// Avoid importing the same holiday again
bool alreadyExists = await _context.Holidays
.AnyAsync(x =>
x.HolidayName == item.HolidayName &&
x.HolidayTypeId == item.HolidayTypeId);
if (alreadyExists)
continue;
// ... create and Add the Holiday as before
}
AnyAsync becomes a fast EXISTS query in SQL Server. With the check enabled, on an empty table:
The table stays at 12 rows. For extra safety, also add a unique index on (HolidayName, HolidayTypeId) in SQL Server, so duplicates are impossible even if two users import at the same moment.
Common errors
1. The specified key does not exist
The bucket was found, but there is no object with that key. Check the folders, spelling and upper/lower case of AWS:FileName; copy the key from the S3 console to be sure.
2. Access Denied
The credentials work but the IAM user has no s3:GetObject permission on the bucket, or the file is in a different AWS account. Check the IAM policy from Step 1. Without s3:ListBucket, a missing file is also reported as Access Denied.
3. No credentials found
The SDK found no keys anywhere in the credential chain. Run aws configure as the same Windows user that runs Visual Studio or the application. When the app runs in IIS, it runs as the application pool identity, which does not see your personal .aws folder; on AWS, use an IAM role instead.
Tip: the forms are created with tag helpers, so they already contain an anti-forgery token. Add [ValidateAntiForgeryToken] to the Preview and Import actions so that ASP.NET Core actually checks it, as explained in authentication in ASP.NET Core MVC.
Interview questions
1. Which NuGet package do you need to read files from S3 in .NET?AWSSDK.S3. It provides AmazonS3Client and GetObjectAsync, and brings in AWSSDK.Core for credentials, regions and request signing.
2. Where should AWS credentials be stored for an ASP.NET Core app?
Not in code or appsettings.json. Locally, in the shared credentials file created by aws configure (or User Secrets / environment variables); on AWS, in an IAM role attached to the server. The SDK finds them through its credential chain.
3. Why is IAmazonS3 registered as a singleton?
The client is thread-safe and keeps a pool of HTTP connections. One shared instance is faster and avoids running out of connections.
4. How do you read an Excel file from S3 without saving it to disk?
Call GetObjectAsync and pass response.ResponseStream to new XLWorkbook(...). Dispose the response afterwards.
5. How does EF Core insert many rows at once?Add each entity, then call SaveChangesAsync once. EF Core batches the inserts (on SQL Server as a MERGE ... OUTPUT statement) in one transaction.
Summary
- Install
AWSSDK.S3,ClosedXMLand EF Core; set up AWS keys once withaws configure. - Keep the region, bucket and file name in
appsettings.json, but never the keys. - Register
IAmazonS3as a singleton in Program.cs with the region from configuration. GetObjectAsync+XLWorkbook(response.ResponseStream)reads the Excel file in memory.- Save with
SaveChangesAsync, and check for existing rows so a second import does not create duplicates.
Related tutorials: import an uploaded Excel file into SQL Server, export data to Excel, service lifetimes in ASP.NET Core, read Excel from S3 in Python.