UseHttpsRedirection on Azure App Service
Recently, when deploying a project, we have hit an interesting issue - when we deployed an ASP.NET Core 2.1 application with HTTPS redirection middleware with HSTS middleware disabled, however the redirection wasn't working correctly.
You will not notice this behavior when you use it along with HSTS middleware since it will perform almost the same action, however without the HSTS middleware it will not do anything.
When you hit the documentation you can see it says that it is going to default to port 443 which is not correct. This behavior has been changed in 2.1.0-rc1 version. I have already submitted a PR to resolve this.
When you go into the HttpsRedirectionMiddleware you can notice that it is trying to detect the HTTPS port in TryGetHttpsPort method with following logic:
- Set in the HttpsRedirectionOptions
- HTTPS_PORT environment variable
- IServerAddressesFeature
- Fail if not set
That basically means that either the server or application has to be configured with the port, else the middleware will treat it like not being configured. Since App Service workers lay behind a reverse proxy which handles HTTPS termination and just passes the X-Forwarded-* headers to the workers which then restore it for the request pipeline in IIS.
So the solution is simple - either go to your Application Settings in App Service and add a setting ASPNETCORE_HTTPS_PORT with value 443. If you don't want to do it in application settings, you can configure the port from within the code:
services.AddHttpsRedirection(options => { options.HttpsPort = 443; });
Quite simple and powerful.
Alternatively, you can also make use of App Service's newly introduced HTTPS Only feature which will result in HTTPS redirect on the server level rather than the application one - it is easier than most of the solution above and works just by flipping a switch - however you have to keep on mind to flip it on with all new deployments and it makes the application slightly more platform dependent.