Skip to main content

ASP.NET Core HTTPS: Enforce SSL & Secure Connections

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() before UseHttpsRedirection() when running behind Nginx, a load balancer, or a container ingress.
  • Enabling HSTS too aggressively. Test with a short MaxAge first. A one-year policy applied to a broken HTTPS setup can lock real users out.
  • Forgetting the HTTPS port. In Docker and Kubernetes, set HttpsPort explicitly 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.json and 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 Secure and use SameSite=Strict for 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.

About csharp-coder.com
Your go-to resource for C#, .NET, and modern software development. Follow along for daily tutorials, tips, and real-world examples.

Comments

Popular posts from this blog

Angular 14 CRUD Operation with Web API .Net 6.0

How to Perform CRUD Operation Using Angular 14 In this article, we will learn the angular crud (create, read, update, delete) tutorial with ASP.NET Core 6 web API. We will use the SQL Server database and responsive user interface for our Web app, we will use the Bootstrap 5. Let's start step by step. Step 1 - Create Database and Web API First we need to create Employee database in SQL Server and web API to communicate with database. so you can use my previous article CRUD operations in web API using net 6.0 to create web API step by step. As you can see, after creating all the required API and database, our API creation part is completed. Now we have to do the angular part like installing angular CLI, creating angular 14 project, command for building and running angular application...etc. Step 2 - Install Angular CLI Now we have to install angular CLI into our system. If you have already installed angular CLI into your system then skip this step.  To install angular CLI ope...

Angular 14 : 404 error during refresh page after deployment

In this article, We will learn how to solve 404 file or directory not found angular error in production.  Refresh browser angular 404 file or directory not found error You have built an Angular app and created a production build with ng build --prod You deploy it to a production server. Everything works fine until you refresh the page. The app throws The requested URL was not found on this server message (Status code 404 not found). It appears that angular routing not working on the production server when you refresh the page. The error appears on the following scenarios When you type the URL directly in the address bar. When you refresh the page The error appears on all the pages except the root page.   Reason for the requested URL was not found on this server error In a Multi-page web application, every time the application needs to display a page it has to send a request to the web server. You can do that by either typing the URL in the address bar, clicking on the Me...

Send an Email via SMTP with MailKit Using .NET 6

How to Send an Email in .NET Core This tutorial show you how to send an email in .NET 6.0 using the MailKit email client library. Install MailKit via NuGet Visual Studio Package Manager Console: Install-Package MailKit How to Send an HTML Email in .NET 6.0 This code sends a simple HTML email using the Gmail SMTP service. There are instructions further below on how to use a few other popular SMTP providers - Gmail, Hotmail, Office 365. // create email message var email = new MimeMessage(); email.From.Add(MailboxAddress.Parse("from_address@example.com")); email.To.Add(MailboxAddress.Parse("to_address@example.com")); email.Subject = "Email Subject"; email.Body = new TextPart(TextFormat.Html) { Text = "<h1>Test HTML Message Body</h1>" }; // send email using var smtp = new SmtpClient(); smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls); smtp.Authenticate("[Username]", "[Password]"); smtp.Se...