How do you enforce that all HTTP requests to an ASP.NET Core application are redirected to HTTPS?
Short answer
The UseHttpsRedirection() middleware, registered early in the pipeline, automatically issues a redirect (307 by default) to the HTTPS equivalent of any incoming HTTP request's URL -- combined with UseHsts() in production (which instructs browsers to never even attempt plain HTTP…
Advertisement
AModel answer
The UseHttpsRedirection() middleware, registered early in the pipeline, automatically issues a redirect (307 by default) to the HTTPS equivalent of any incoming HTTP request's URL -- combined with UseHsts() in production (which instructs browsers to never even attempt plain HTTP after the first successful HTTPS visit), this ensures the application is never served meaningfully over unencrypted HTTP.
var app = builder.Build();
if (!app.Environment.IsDevelopment()) {
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();Real-world example
A banking API redirects every plain HTTP request to its HTTPS equivalent automatically, ensuring that even a user who mistakenly types http:// instead of https:// in their browser is immediately and transparently redirected to the secure version.
Likely follow-ups
- What HTTP status code does the redirect use, and why does that choice matter for caching?
- What's the difference between HTTPS redirection and HSTS, and why do you need both?
Related topics