Wahlin on .NET

Requiring SSL for MVC Controllers

ASP.NET MVC provides a lot of flexibility when it comes to changing how controllers, actions, routes and more work within an application. Having flexibility is good especially when you need to make a modification quickly without having to write a lot of code to get the change in place.

My company is in the process of rolling out an ASP.NET MVC site for a client and specific actions and controllers need to have SSL running to ensure that no sensitive information gets out, such as passwords and credit cards. If a user visits the site using http:// I need to switch them to https:// in certain parts of the Web site. Fortunately, ASP.NET MVC is quite extensible so it only took about four to five minutes to get a simple solution in place.

The easiest way I know of to switch to SSL for specific controllers or actions is to create an ActionFilterAttribute that handles redirecting them to an https:// address. Classes that derive from ActionFilterAttribute can be placed immediately above actions or even controllers in cases where the filter needs to apply to all actions in the controller. For my situation I needed entire controllers to be SSL-enabled so I placed the attribute above the controller class name.

Here's an example of the simple RequiresSSL attribute class:

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
  public class RequiresSSL : ActionFilterAttribute
  {
    public override void OnActionExecuting(
     ActionExecutingContext filterContext)
    {
      HttpRequestBase req = filterContext.HttpContext.Request;
      HttpResponseBase res = filterContext.HttpContext.Response;

      //Check if we're secure or not and if we're on the local box
      if (!req.IsSecureConnection && !req.IsLocal)
      {
        string url = req.Url.ToString().ToLower()
         .Replace("http:", "https:");
        res.Redirect(url);
      }
      base.OnActionExecuting(filterContext);
    }
  }
}

Some may note that the ToLower() call shown previously could cause consequences with QueryString data. I could take ToString() out but some people may type "HTTP" instead of "http", which would mess up the replace call. For the current application I'm working on, I only have integers being passed around on the QueryString so it didn't affect me at all, but it definitely could affect string data being passed. The solution is to use the UriBuilder class, which works much better in this scenario. Here's a different version of the RequiresSSL class that uses the UriBuilder class to create the SSL redirect URL.

using System;
using System.Web;
using System.Web.Mvc;

namespace Helpers
{
  public class RequiresSSL : ActionFilterAttribute
  {
    public override void OnActionExecuting(
    ActionExecutingContext filterContext)
    {
      HttpRequestBase req = filterContext.HttpContext.Request;
      HttpResponseBase res = filterContext.HttpContext.Response;

      //Check if we're secure or not and if we're on the local box
      if (!req.IsSecureConnection && !req.IsLocal)
      {
        var builder = new UriBuilder(req.Url)
        {
          Scheme = Uri.UriSchemeHttps,
          Port = 443
        };
        res.Redirect(builder.Uri.ToString());
      }
      base.OnActionExecuting(filterContext);
    }
  }
}

The RequiresSSL attribute can then be placed above the appropriate action or controller:

 [HandleError]
[RequiresSSL]
public class AccountController : Controller
{
  ...
}

If you're running IIS7 and want to get a test SSL certificate setup for testing purposes, check out my good friend Rob Bagby's excellent post on the subject. He walks through the process of creating self-signed certificates and using them on your server.

About the Author

Dan Wahlin (Microsoft MVP for ASP.NET and XML Web Services) is the founder of The Wahlin Group which specializes in .NET and SharePoint onsite, online and video training and consulting solutions. Dan also founded the XML for ASP.NET Developers Web site, which focuses on using ASP.NET, XML, AJAX, Silverlight and Web Services in Microsoft's .NET platform. He's also on the INETA Speaker's Bureau and speaks at conferences and user groups around the world. Dan has written several books on .NET including "Professional Silverlight 2 for ASP.NET Developers," "Professional ASP.NET 3.5 AJAX, ASP.NET 2.0 MVP Hacks and Tips," and "XML for ASP.NET Developers." Read Dan's blog here.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events