X

Asp .NET Redirect To SSL HttpModule

asp.net

There are tones of blog post out there on how to redirect http to https. As in when a user request for http://myserver.com/Login.aspx
they will be redirected to https://myserver.com/Login.aspx

One can do it with IIS but I find that way a bit ugly since you have to create another site and set the 403 to redirect to another location. Not as elegant as apache mod rewrite.

A more elegant approach I found when using asp .net is by using an HttpModule in your code, so that the entire site is redirected. There are other solutions to redirect individual pages but for this post we will focus on redirecting all traffic to SSL.

To begin with we will code up an RedirectToSSL.cs page and place it into our App_Code folder.

using System;
using System.Web;

namespace SolutionName.App_Code
{
    public class RedirectToSSL : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
           
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += ContextBeginRequest;
        }


        private static void ContextBeginRequest(object sender, EventArgs e)
        {

            HttpApplication application = sender as HttpApplication;

            if (application == null) 
                return;

            if (application.Request.IsSecureConnection) 
                return;
        
            // send user to SSL 

            string serverName = HttpUtility.UrlEncode(application.Request.ServerVariables["SERVER_NAME"]);

            string filePath = application.Request.FilePath;

            application.Response.Redirect("https://" + serverName + filePath);
        }

        #endregion

    }
}

Then all we have to do is add this line in our web.config file in order to enable it.


     

Replace the solutionName with your project name and voila you now have the entire site in SSL and you don’t have to worry about talking to an admin for IIS configuration or anything like that.

Categories: .NET ASP .NET
Taswar Bhatti:

View Comments (4)

  • Hi Taswar,

    Great article! When I did this for IIS 7.5, it gave me an error and said for me to start without debugging so I did. It then gave me an apparent error in IIS 7.5 which said:

    "HTTP Error 500.22 - Internal Server Error

    An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode."

    Any idea what I really need to do to fix that? When I googled the error message I only got 6 results and each of those was referencing specific installation issues with certain software. I sure hope I can get your example here working for me as it will be one of the best time savers I have ever found in the .NET world! Thanks for any input! :)

Related Post