Force ASP.NET web application to use SSL

Published on
12,393 Points
2 Endorsements
Last Modified:
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.

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.

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
  ' Fires at the beginning of each request
  'Require SSL
  If (Request.UserHostName <> "" _
	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
      End If
  End If
End Sub 
public void Application_BeginRequest(object sender, EventArgs e)
  if (Request.UserHostName != "" && 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"];

Open in new window


Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Join & Write a Comment

Wrapper-1-Query. Use an Excel function to calculate a column for an Access query. Part 1. Shows a query in Access that has a calculated column with the results of an Excel worksheet function. See how to call a wrapper function from a query, and …
Watch this online video tutorial and learn the best way to reduce Outlook mailbox size using Compact Now feature of Outlook. It removes the deletes item's space from Microsoft Outlook 2016, 2013, and 2010 and compresses the PST file size. This will …

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month