THE EXPERIENCED

Software Engineer - Back-End Developer / Front-End Developer

Force ASP.NET Page to Use secure HTTP (https) with SSL/TLS

Sometimes we want to provide encryption and secure identification of the server creating a secure channel over an insecure network. In that case we need HTTPS connection which ensures reasonable protection e.g. for payment transactions.

Ok let’s see how this thing works.

Say that your page is as follows: http://www.domain.com/yourpage.aspx
If you have an ASP.NET WebForms project, just add this code inside Load Event Handler and voila! That’s it!

VB.NET:

    If Not Request.IsSecureConnection Then
        Response.Redirect("https://www.domain.com/yourpage.aspx ")
    End If
C#.NET:

    if(!Request.IsSecureConnection){
        Response.Redirect("https://www.domain.com/yourpage.aspx");
    }

As for ASP.NET Core Razor Pages, you just need to add a middleware for redirecting HTTP requests to HTTPS.

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
    app.UseHttpsRedirection();
}

Hope this helps someone