Securing your ASP.NET Core applications is non-negotiable in today’s cyber-threat landscape. By enforcing HTTPS, HSTS, and TLS, you ensure encrypted communication between clients and servers, protecting sensitive data from interception and attacks.
This guide provides a step-by-step, end-to-end implementation from development to production.
Prerequisites
Visual Studio 2022 or later with ASP.NET Core workload installed
.NET 7 or later
Basic understanding of ASP.NET Core MVC/Web API
Optional: Docker/Kubernetes for production deployment.
Step 1: Create an ASP.NET Core Web API Project
Open Visual Studio → Create a new project → Select ASP.NET Core Web API.
Choose .NET 7 , enable HTTPS , and leave Authentication as “None” for now.
Click Create.
You now have a basic Web API project with HTTPS support enabled by default (self-signed certificate for development).
Step 2: Enforce HTTPS
Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Force all HTTP requests to HTTPS
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
launchSettings.json
"profiles": {
"MyApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
With this, your app automatically redirects HTTP requests to HTTPS during development.
Step 3: Enable HSTS (HTTP Strict Transport Security)
HSTS tells browsers to always connect via HTTPS , preventing downgrade attacks.
Add Middleware
if (!app.Environment.IsDevelopment())
{
// Enable HSTS in production only
app.UseHsts();
}
app.UseHttpsRedirection();
Optional HSTS Options
app.UseHsts(options =>
{
options.MaxAge = TimeSpan.FromDays(365); // enforce for 1 year
options.IncludeSubDomains = true;
options.Preload = true;
});
Important: Do not enable HSTS during development; browsers may cache HSTS headers and block HTTP requests.
Step 4: Configure TLS in Kestrel
ASP.NET Core uses Kestrel as the web server. Configure TLS to enforce secure protocols.
appsettings.json
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:5001",
"Certificate": {
"Path": "certs/devcert.pfx",
"Password": "StrongPassword123!"
}
}
}
}

Join the conversation! Your thoughts help the community grow.