liveBook · Manning

HttpsRedirectionMiddleware

As explained in ASP.NET Core in Action, 3e

HttpsRedirectionMiddleware is ASP.NET Core middleware that redirects HTTP requests to their HTTPS equivalents.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains registration, pipeline behavior, status codes, endpoint selection, missing configuration, and alternate-port configuration.
Examples
Uses Program.cs registration, a 307 redirect, an absent-port warning, and ASPNETCORE_HTTPS_PORT configuration as concrete examples.
What it assumes
Assumes familiarity with Program.cs and middleware pipelines while establishing HTTPS redirection behavior and endpoint requirements.
What you can do after
Operate/configure HTTPS redirection in an ASP.NET Core pipeline and diagnose missing HTTPS endpoint or port configuration.
How it connects
Connects HTTPS redirection with HSTS, reverse proxies, TLS certificates, and HTTPS endpoint configuration.

Also explained in

Compare how 2 books explain HttpsRedirectionMiddleware →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.