jQuery and ASP.NET

December 12, 2009

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

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Redirect from HTTP to HTTPS in ASP.NET"
  1. Enrique said...
    May 25, 2010 11:02 AM

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

  2. Blackjack said...
    May 25, 2010 8:44 PM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions