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

2 comments:

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

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

    ReplyDelete