HttpsRedirectionMiddleware redirects HTTP requests to their HTTPS equivalents, enforcing secure access across an ASP.NET Core application. An HTTP request is short-circuited with a redirect, and the browser repeats it over HTTPS. section 28.4.2
Listing 28.4 Using HttpsRedirectionMiddleware
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddHsts(o => options.MaxAge = TimeSpan.FromHours(1));
WebApplication app = builder.Build();
if(app.Environment.IsProduction())
{
app.UseHsts();
}
app.UseHttpsRedirection(); #1
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.Run();
#1 Adds the HttpsRedirectionMiddleware to the pipeline and redirects all HTTP requests to HTTPS
Register the middleware with app.UseHttpsRedirection() in Program.cs, typically after error handling and HSTS configuration. section 28.4.2
Key behavior and configuration points:
- Uses HTTP 307 Temporary Redirect by default. section 28.4.2
- Redirects to the first configured HTTPS endpoint. section 28.4.2
- Logs a warning instead of redirecting when no HTTPS endpoint is configured. section 28.4.2
- Supports an alternate redirect port through the ASPNETCORE_HTTPS_PORT environment variable, which can help behind a reverse proxy. section 28.4.2
Typical pipeline registration
After building the application, call app.UseHttpsRedirection() before static files, routing, and endpoint mapping. Pair it with HSTS for stronger browser-side HTTPS enforcement. section 28.4.2

