views:

665

answers:

1

Ok, so I want to force https/ssl on parts of my ASP.NET MVC site. Found lots of great sources including an ActionFilter here: http://blog.tylergarlick.com/index.php/2009/07/mvc-redirect-to-http-and-https/

Whenever I enable the ActionFilter however I end up in a redirect loop. The problem is that if I type https://www.mysite.com/ into the address bar, request.url is always equal to http://www.mysite.com/.

The code for the action filter is below and to my knowledge I'm not doing any url rewriting, redirecting, custom routing or modifying the url beyond the standard setup. Are there any common/uncommon reasons why this might be happening and/or any workarounds or fixes? The site is currently hosted at NetworkSolutions - is there a chance it's related to IIS configuration? Any assistance would be much appreciated.

public class RedirectToHttps : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Helpers just so I don’t have to type so much
        var request = filterContext.HttpContext.Request;
        var response = filterContext.HttpContext.Response;

        // Make sure we’re in https or local
        if (!request.IsSecureConnection && !request.IsLocal)
        {
            string redirectUrl = request.Url.ToString().Replace("http:", "https:");
            response.Redirect(redirectUrl);
        }

        base.OnActionExecuting(filterContext);
    }
}
+1  A: 

Even though you're not doing any explicit URL rewriting, it is done by the ASP.NET MVC engine. You can probably retrieve the original URL with HttpContext.Request.RawUrl

Thomas Levesque
Thanks for taking the time to answer my question. It seems that RawUrl is only giving me the relative path: /default.aspx for instance. Is this normal?
I thought it contained the original URL, but according to the documentation : "The raw URL is defined as the part of the URL following the domain information". Sorry...
Thomas Levesque