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

C#

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
Response.Redirect(uri.ToString());
}
}

VB.NET

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

' Redirect to https
Response.Redirect(uri.ToString())
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.

2 comments:

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