Redirect from HTTP to HTTPS in ASP.NET

Here’s a simple way to redirect a user from HTTP to HTTPS. I have tested a few scenarios with the code and it has worked fine. Let me know if you face any issues with the code


protected void Page_Load(object sender, EventArgs e)
if (!Request.IsSecureConnection)
UriBuilder uri = new UriBuilder(Page.Request.Url);
uri.Scheme = Uri.UriSchemeHttps;

// Redirect to https


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Request.IsSecureConnection Then
uri As New UriBuilder(Page.Request.Url)
uri.Scheme = Uri.UriSchemeHttps

' Redirect to https
End If
End Sub
The IsSecureConnection property of the HttpRequest class gets a value indicating whether the HTTP connection uses secure sockets. Is not, the uri scheme is changed to https and the user is redirected

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.


Enrique said...

When I tried, this code leaves the port to 80, I missed something?

Blackjack said...

Probably if you explain what you did someone could help you out. I tried it at my end without any issues