Rejecting HTTP requests with custom ProblemDetails middleware
In this recipe, we’ll create middleware that enforces HTTPS for all incoming requests to your ASP.NET Core Web API. While it’s ideal to configure your web server or load balancer (e.g., IIS, NGINX) to exclusively handle HTTPS traffic, implementing HTTPS-enforcing middleware provides an additional layer of security. This ensures HTTPS enforcement regardless of deployment configuration.
While ASP.NET Core provides HTTP Strict Transport Security (HSTS) to enforce HTTPS connections in web browsers (assuming the web browser respects HSTS), this HSTS implementation has some limitations: For example, it does not affect API clients such as mobile apps or desktop applications. Further, the first request is still vulnerable (until the HSTS header is received). To address these limitations, we’ll create middleware that enforces HTTPS for all incoming requests, regardless of client type.
Our custom HTTPS middleware...