Enforce HTTPS in ASP.NET Core Razor Pages

Razor Pages are a new feature of ASP.NET Core 2.0 that makes coding page-focused scenarios easier and more productive. Razor Pages are introduced with the intent of creating page focused scenarios where there is no real logic is involved. You can find all my razor pages posts here. The latest version (2.1) of ASP.NET Core supports HTTPS by default, but at the time of writing this post, it is still in the preview release. You can find all my ASP.NET Core 2.1 posts here. The app built on ASP.NET Core 2.0 version needs to be secured manually. In this post, we will see how to enforce HTTPS in ASP.NET Core Razor Pages applications.

Enforce HTTPS in ASP.NET Core Razor Pages

There are 2 ways to enforce HTTPS in ASP.NET Core Razor Pages.

RequireHttps Attribute

URL Rewriting

RequireHttps Attribute

The RequireHttps attribute is an authorization filter that confirms requests are received over HTTPS. If the request comes via HTTP, it will be redirected to the HTTPS version of the request URI if the GET method was used. The attribute can be applied to a PageModel class or globally for the application. You can apply to the PageModel class like,

So when the request comes from HTTP, the redirection happens to HTTPS. This results in 302 status code indicates that the item has been moved temporarily to a different URL to the one originally used in the request (no 301). To fix this, set the permanent property of the RequireHttps attribute to true:

Please note that if you run this application on IISExpress, it will not work because we have not configured IIS Express to allow SSL. To Enable SSL, right-click on Project -> select properties -> navigate to debug tab. On debug tab, check Enable SSL option.

That’s it.

To conclude, we just saw that it’s easy to enforce HTTPS in ASP.NET Core application. With ASP.NET Core 2.1, we don’t have to worry about this.

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then