I want my login page to be SSL only:
[RequireHttps] public ActionResult Login() { if (Helper.LoggedIn) { Response.Redirect("/account/stats"); } return View(); }
But obviously it doesn't work on localhost when I develop and debug my application. I don't wanna use IIS 7 with SSL certificates, how can I automatically disable the RequireHttps attribute?
Update
Based on info provided by StackOverflow users and ASP.NET MVC 2 source code I created the following class that solves the problem.
public class RequireSSLAttribute : FilterAttribute, IAuthorizationFilter { public virtual void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (!filterContext.HttpContext.Request.IsSecureConnection) { HandleNonHttpsRequest(filterContext); } } protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.Url.Host.Contains("localhost")) return; if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("The requested resource can only be accessed via SSL"); } string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(url); } }
And it's used like this:
[RequireSSL] public ActionResult Login() { if (Helper.LoggedIn) { Response.Redirect("/account/stats"); } return View(); }
The easiest thing would be to derive a new attribute from RequireHttps and override HandleNonHttpsRequest
protected override void HandleNonHttpsRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.Request.Url.Host.Contains("localhost")) { base.HandleNonHttpsRequest(filterContext); } }
HandleNonHttpsRequest is the method that throws the exception, here all we're doing is not calling it if the host is localhost (and as Jeff says in his comment you could extend this to test environments or in fact any other exceptions you want).
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { if (!HttpContext.Current.IsDebuggingEnabled) { filters.Add(new RequireHttpsAttribute()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With