Learn how to enforce HTTPS in ASP.NET Core with SSL, HSTS, and redirection. Secure your web app with this step-by-step C# tutorial. Start now!
If you're building a web application, securing it with ASP.NET Core HTTPS is no longer optional — it's a baseline requirement. Browsers flag plain HTTP sites as "Not Secure," search engines penalize them, and attackers actively exploit unencrypted traffic on public networks. The good news? ASP.NET Core ships with built-in middleware to enforce SSL, redirect insecure requests, and harden your app with HSTS. In this tutorial you'll learn exactly how to enforce HTTPS in ASP.NET Core, why each setting matters, and the common pitfalls that trip up even experienced developers.
Whether you're a beginner wondering how to enable SSL, an intermediate developer searching for best practices, or a senior engineer hardening a production deployment, this guide covers the full picture — from development certificates to production-grade configuration.
Why ASP.NET Core HTTPS Matters for Security
HTTPS (Hypertext Transfer Protocol Secure) encrypts the data exchanged between a client and your server using TLS (Transport Layer Security, the modern successor to SSL). Without it, every request — including login credentials, session cookies, API tokens, and personal data — travels across the network in plain text. Anyone positioned between the user and your server, such as on an open coffee-shop Wi-Fi network, can read or tamper with that traffic. This is the classic man-in-the-middle attack.
Enforcing ASP.NET Core SSL delivers three core security guarantees:
- Confidentiality — data is encrypted so eavesdroppers can't read it.
- Integrity — tampering is detected, so attackers can't silently modify responses (for example, injecting malicious scripts).
- Authentication — the TLS certificate proves your server is who it claims to be, preventing impersonation.
Beyond security, HTTPS is also an SEO ranking signal, a requirement for HTTP/2 and HTTP/3, and mandatory for modern browser features like service workers and the Geolocation API. In short, there's no good reason to ship without it.
How to Enforce HTTPS in ASP.NET Core
ASP.NET Core gives you two complementary tools that work together: HTTPS redirection middleware (which upgrades incoming HTTP requests to HTTPS) and HSTS (which tells the browser to never use HTTP again). When you create a new project with the default template, both are already wired up. Here's what the minimal hosting model in Program.cs looks like:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
// Adds the Strict-Transport-Security header in production only
app.UseHsts();
}
// Redirects all HTTP requests to HTTPS
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.Run();
The order matters. UseHttpsRedirection() should sit early in the pipeline so insecure requests are upgraded before any other middleware processes them. Notice that UseHsts() is wrapped in an environment check — you almost never want HSTS active during local development, and we'll explain why shortly.
Configuring HTTPS Redirection Middleware
By default, UseHttpsRedirection() issues a temporary 307 redirect. For production, you typically want a permanent 308 redirect and an explicit HTTPS port. Configure it like this:
builder.Services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
Why a 308 instead of 307? A permanent redirect tells browsers and search engines that the HTTPS version is the canonical address, so they cache the redirect and stop hitting the insecure endpoint. This improves both performance and SEO. The HttpsPort setting removes ambiguity in containerized or reverse-proxy environments where the framework can't always infer the correct port automatically.
Hardening Your App with HSTS
HTTP Strict Transport Security (HSTS) is a response header that instructs the browser to only communicate with your domain over HTTPS for a specified duration — even if a user types http:// manually or clicks an old HTTP link. This closes a subtle gap: the very first redirect from HTTP to HTTPS is itself unencrypted and can be hijacked. Once HSTS is cached, the browser never sends that first insecure request again.
builder.Services.AddHsts(options =>
{
options.MaxAge = TimeSpan.FromDays(365);
options.IncludeSubDomains = true;
options.Preload = true;
});
Here's what each option does and why it's important:
- MaxAge — how long the browser remembers to force HTTPS. Start small (e.g. a few days) when testing, then increase to one year (or two) once you're confident.
- IncludeSubDomains — applies the policy to every subdomain. Only enable this if all subdomains support HTTPS.
- Preload — allows you to submit your domain to the browser preload list so HTTPS is enforced before the user even visits for the first time.
Warning: HSTS is sticky. Because the browser caches it for the full MaxAge, a misconfiguration can lock users out of your site until the policy expires. This is exactly why the default template disables HSTS in development — you don't want your browser permanently forcing HTTPS on localhost.
Setting Up SSL Certificates in ASP.NET Core
For local development, the .NET SDK includes a self-signed development certificate. You can trust it on your machine with a single command:
// Run these in your terminal, not in C#:
// dotnet dev-certs https --trust (Windows/macOS)
// dotnet dev-certs https --clean (remove and regenerate if it breaks)
In production, you need a certificate issued by a trusted Certificate Authority (CA). Most teams handle TLS termination at the infrastructure layer — using a reverse proxy like Nginx, a cloud load balancer (Azure App Service, AWS ALB), or a service like Let's Encrypt for free automated certificates. When TLS terminates at a proxy, your app receives plain HTTP internally, so you must configure forwarded headers to preserve the original scheme:
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
var app = builder.Build();
// Must run BEFORE UseHttpsRedirection so the app knows the request was secure
app.UseForwardedHeaders();
app.UseHttpsRedirection();
Without UseForwardedHeaders(), the redirection middleware sees an HTTP request from the proxy and triggers an infinite redirect loop — one of the most common production HTTPS bugs. If you'd rather configure Kestrel to serve HTTPS directly (for example, in a self-hosted scenario), you can bind a certificate in appsettings.json:
// appsettings.json
// {
// "Kestrel": {
// "Endpoints": {
// "Https": {
// "Url": "https://*:443",
// "Certificate": {
// "Path": "/certs/mysite.pfx",
// "Password": "your-secret-password"
// }
// }
// }
// }
// }
Never commit certificate passwords to source control. Use environment variables, the .NET Secret Manager, or a secrets vault such as Azure Key Vault instead.
Securing Cookies Over HTTPS
Enforcing HTTPS at the transport layer is only half the job. You should also ensure that authentication and session cookies are never sent over an insecure connection. Mark them as Secure so the browser only transmits them over HTTPS:
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.Secure = CookieSecurePolicy.Always;
options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
// Later in the pipeline:
app.UseCookiePolicy();
Combining the Secure flag with SameSite=Strict protects against both eavesdropping and cross-site request forgery (CSRF). This is a small change with a big payoff for overall application security.
Common Pitfalls and Best Practices
Even with the right middleware, teams routinely make the same mistakes. Here are the issues to watch for when you enforce HTTPS in ASP.NET Core:
- Infinite redirect loops behind a proxy. Always add
UseForwardedHeaders()beforeUseHttpsRedirection()when running behind Nginx, a load balancer, or a container ingress. - Enabling HSTS too aggressively. Test with a short
MaxAgefirst. A one-year policy applied to a broken HTTPS setup can lock real users out. - Forgetting the HTTPS port. In Docker and Kubernetes, set
HttpsPortexplicitly so redirection targets the right address. - Mixed content. Loading scripts, images, or stylesheets over HTTP on an HTTPS page breaks the security guarantee and triggers browser warnings. Use protocol-relative or absolute HTTPS URLs.
- Hardcoding certificate secrets. Keep passwords and private keys out of
appsettings.jsonand source control. - Skipping security headers. Pair HTTPS with a Content Security Policy and other headers for defense in depth.
A solid best-practice checklist looks like this: redirect all HTTP to HTTPS with a 308, enable HSTS with preload in production only, terminate TLS with an automated CA certificate, mark cookies as secure, and verify there's no mixed content. Run your domain through a tool like SSL Labs to confirm your TLS configuration scores an A rating.
Conclusion: Key Takeaways for ASP.NET Core HTTPS
Securing your application with ASP.NET Core HTTPS is one of the highest-impact, lowest-effort improvements you can make. The framework does most of the heavy lifting — you just need to configure it correctly and understand why each piece exists.
Here are the essential takeaways:
- Use
UseHttpsRedirection()to upgrade insecure requests, ideally with a permanent 308 redirect. - Enable
UseHsts()in production to force browsers to stick with HTTPS — but never on localhost. - When running behind a proxy or load balancer, configure forwarded headers to avoid redirect loops.
- Mark cookies as
Secureand useSameSite=Strictfor layered protection. - Use trusted CA certificates in production and keep secrets out of source control.
Get these fundamentals right and you'll ship a web app that encrypts every connection, satisfies modern browser and SEO requirements, and protects your users from man-in-the-middle attacks. Apply these ASP.NET Core SSL best practices today, and make secure-by-default the standard for every project you build.
Your go-to resource for C#, .NET, and modern software development. Follow along for daily tutorials, tips, and real-world examples.
Comments
Post a Comment