This Action Filter doesn’t seem to work consistently. Some times it turns SSL off and sometimes it doesn’t. I have it applied to the entire controller at it’s declaration.
public class SSLFilter:ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase req = filterContext.HttpContext.Request;
HttpResponseBase res = filterContext.HttpContext.Response;
if (req.IsSecureConnection)
{
var builder = new UriBuilder(req.Url)
{
Scheme = Uri.UriSchemeHttp,
Port = 80
};
res.Redirect(builder.Uri.ToString());
}
base.OnActionExecuting(filterContext);
}
}
It’s kind of odd…any ideas why it might be working sporadically?
Have you tried decorating your controllers/actions with the
[RequireHttps]attribute?Oops, haven’t noticed you was asking about ASP.NET MVC 2. This attribute is available in ASP.NET MVC 3 only, so here’s the source code for it (as implemented in ASP.NET MVC 3):
Notice that how instead of doing any redirects it uses a RedirectResult which is the correct way of performing redirects in ASP.NET MVC => by returning action results:
Not only that this will perform the correct redirect but that’s how to short-circuit the execution of an action. Also semantically your filter should actually be an IAuthorizationFilter as you are blocking access to some resource here.