BeanSoftware Logo

ASP.NET Database Search Control

    Write For Us

HTTP To HTTPS Redirection In ASP.NET

If you use Secure Socket Layer (SSL) connection then you don't want to allow access through HTTP. If someone tries to visit secure page with http:// that visitor should be redirected to URL starting with HTTPS. There is a few different solutions to this problem, depending of your specific case.

To find does visitor use secure connection use Request.IsSecureConnection property. For example, let say you need to use secure connection on just one or two pages. In that case, you can do it in Page_Load event by using the code like this:

[ C# ]

protected void Page_Load(object sender, EventArgs e)
 // check is secure connection used
 if (!Request.IsSecureConnection)
   // redirect visitor to SSL connection
   Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));


[ VB.NET ]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 ' check is secure connection used
 If Not Request.IsSecureConnection Then
   ' redirect visitor to SSL connection
   Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))
 End If
End Sub

In case that you need this functionality in some area of your site (e.g. /admin), you can place this code in master page instead of copying it in every single web page. In case that you want to use it on complete site, then place redirection in Global.asax file in Application_BeginRequest. Or, for the same purpose you can create custom HTTP module. More about how to create HTTP modules you can find at Create Your Own HTTP Module tutorial.

Note: Every solution that uses ASP.NET will affect only ASP.NET files. If you need to switch to HTTPS protocol when other file types are requested, you need to set up SSL with IIS.

Related articles:

1. Security Features in ASP.NET 2.0
2. How to redirect page permanently with status code 301?

FAQ toolbar: Submit FAQ  |  Tell A Friend  |  Add to favorites  |  Feedback

Copyright © 2002-2008 Bean Software. All rights reserved.