Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect away from HTTPS with ASP.NET MVC App

I'm using ASP.NET MVC 2 and have a login page that is secured via HTTPS. To ensure that the user always accesses those pages via SSL, I've added the attribute [RequireHttps] to the controller. This does the job perfectly.

When they have successfully logged in, I'd like to redirect them back to HTTP version. However, there isn't a [RequireHttp] attribute and I'm struggling to get my head around how I might achieve this.

The added (potential) complication is that the website when in production is hosted at the route of the domain, but for development and testing purposes it is within a sub directory / virtual directory / application.

Am I over-thinking this and is there an easy solution staring me in the face? Or is it a little more complex?

like image 375
Amadiere Avatar asked Apr 01 '10 13:04

Amadiere


1 Answers

After a bit of digging, I went along the lines of rolling my own as there didn't appear to be a good built-in solution to this (as mentioned, there is a great one for MVC2 applications in the form of [RequireHttps]). Inspired by çağdaş's solution to this problem and I adapated to come up with the following code:

public class RequireHttp : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // If the request has arrived via HTTPS...
        if (filterContext.HttpContext.Request.IsSecureConnection)
        {
            filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.ToString().Replace("https:", "http:")); // Go on, bugger off "s"!
            filterContext.Result.ExecuteResult(filterContext);
        }
        base.OnActionExecuting(filterContext);
    }
}

I can now add this to my Controller methods and it behaves (seemingly) as expected. If I redirect to the Index action on my controller from a HTTPS protocol, it will redirect to HTTP. It only allows HTTP access to the Index ActionResult.

[RequireHttp]
public ActionResult Index() {
    return View();
}
like image 150
Amadiere Avatar answered Sep 20 '22 13:09

Amadiere