Ikaros
Ikaros

Reputation:

Why is HttpContext.Request.Url not matching what's in the address bar?

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);
    }
}

Upvotes: 1

Views: 2702

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292575

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

Upvotes: 2

Related Questions