Configure ASP.NET MVC controller to use SSL or Not to use SSL

This article explains how to configure a controller or a controller action to use SSL or Not to use SSL or use SSL only on a production server

If you are developing an asp.net mvc app that uses SSL for some of its pages, you need a robust way to make sure that all the requests for that page will use https:// connections. Luckily for us microsoft has come up with the RequireHttps Attribute. When you decorate a controller action with the RequireHttps Attribute, all the requests for that action will be forced to use SSL.

But there’s a catch. If you use that attribute, the page will ask for an SSL connection even on the visual studio development server (casini) and as casini does not support SSL, you cannot debug the page 🙁

So we need to customize the RequireHttpsAttribute to order it to ask for SSL only for remote servers and not in localhost. Luckily for us .net framework 2.0 source is available so we can get the attributes source and modify it.

 

Here’s the modified code to use SSL only for remote hosts

namespace System.Web.Mvc
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Web.Mvc.Resources;

    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
        Justification = "Unsealed because type contains virtual extensibility points.")]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class RequireHttpsProdAttribute : FilterAttribute, IAuthorizationFilter
    {

        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //modified to check for local requests since cant use ssl for dev server. (casini)
            if (!filterContext.HttpContext.Request.IsSecureConnection && !filterContext.HttpContext.Request.IsLocal)
            {
                HandleNonHttpsRequest(filterContext);
            }
        }

        protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext)
        {
            // only redirect for GET requests, otherwise the browser might not propagate the verb and request
            // body correctly.

            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("Requests to the given url must use SSL");
            }

            // redirect to HTTPS version of page
            string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(url);
        }

    }
}

 

Save the above code as RequirehttpsAttribute.cs and …. that’s it.

Now go to your controller action and add the following attribute to it [RequireHttpsProd(Order = 1)]

Adding the attribute to the controller will apply it to all the controller actions in that controller.

Now there’s another issue. When the user is in a page with SSL, all the relative links he visit from it will be https://… ones. So how to force user to use a non SSL connections to some pages in your site ?

It’s simple just turn the require https attribute upside down. Like this 🙂

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web
{
    public class NotRequireHttpsAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;

            if (request.IsSecureConnection && !request.IsLocal)
            {
                string redirectUrl = request.Url.ToString().Replace("https:", "http:");
                response.Redirect(redirectUrl);
            }
            base.OnActionExecuting(filterContext);
        }
    }
}

 

Save the above code as NotRequireHttpsAttribute.cs and apply the attribute NotRequireHttps to controllers or actions that need non SSL connections.

Well that’s it,

 

Happy Coding…