<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Force ASP.NET web application to use SSL

Published on
12,457 Points
6,257 Views
2 Endorsements
Last Modified:
Approved
If your ASP.NET application requires SSL, then you should make sure that user uses https: instead of http: to access your application, and your ASP.NET application should have the ability to automatically switch to the secure mode (https) if user comes to the application from a non-secure mode (http).

The easiest way to implement this feature is to use Global.asax's Application_BeginRequest function, where it checks if the request comes from a "HTTPS" protocol, if not, then changes "http" to "https" and then redirecst the request to the secure location.

The code snippets for VB.NET and C# are attached.


Note:
If the application is running on a local machine during the development phase, we should not try to redirect the request to a secure link, that is why there are some checks in the first couple of lines of code.

 
'VB.NET
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
  ' Fires at the beginning of each request
  'Require SSL
  If (Request.UserHostName <> "127.0.0.1" _
	AndAlso Request.UserHostName <> "localhost") Then
      If Request.ServerVariables("HTTPS") = "off" Then
        Dim redir As String = "https://"   Request.ServerVariables("SERVER_NAME")   Request.ServerVariables("SCRIPT_NAME")
        If Request.ServerVariables("QUERY_STRING") <> "" Then
          redir  = "?"   Request.ServerVariables("QUERY_STRING")
        End If
        Response.Redirect(redir)
      End If
  End If
End Sub 
//C#
public void Application_BeginRequest(object sender, EventArgs e)
{
  if (Request.UserHostName != "127.0.0.1" && Request.UserHostName != "localhost")
  {
    if (Request.ServerVariables["HTTPS"] == "off")
	{
	  string redir = "https://"   Request.ServerVariables["SERVER_NAME"]   Request.ServerVariables["SCRIPT_NAME"];
	  if (Request.ServerVariables["QUERY_STRING"] != "")
	  {
	    redir  = "?"   Request.ServerVariables["QUERY_STRING"];
	  }
	  Response.Redirect(redir);
	}
  }
}

Open in new window

2
Comment
Author:prairiedog
0 Comments

Featured Post

Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

Join & Write a Comment

Learn how to collaborate with office 365 Office Online
Please check the video also in regards to recovery of deleted emails from office 365 admin center and through the MFCMAPI tool. I have mentioned each and every step with the proper steps that need to be taken care of.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month