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

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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