Jared
Jared

Reputation: 6060

MVC3 after [RequireHttps] how to ensure non https is used

I found This Post and it looks like what I was needing for an application, my question is how do you revert back to plain http when https is no longer needed? Will it inherently do this based on an action not having the [RequireHttps] annotation?

EDIT: I found a couple posts talking about moving from https to http (here & here). However, I'd still appreciate an answer to the question below.

Alternately, I had debated on having the application open in a new window. Is it a fair assumption that the https will only apply to the new window?

Upvotes: 6

Views: 3955

Answers (2)

Chris Baxter
Chris Baxter

Reputation: 16353

ASP.NET MVC's RequireHttps only goes one way. In the past I have just created my own FilterAttribute implementation to allow travel both ways:

EnsureHttpsAttribute

  public class EnsureHttpsAttribute : FilterAttribute, IAuthorizationFilter
  {
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      Verify.NotNull(filterContext, "filterContext");
      Verify.True(filterContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase), "filterContext");

      var request = filterContext.HttpContext.Request;
      if (request.Url != null && !request.IsSecureConnection && !request.IsLocal)
        filterContext.Result = new RedirectResult("https://" + request.Url.Host + request.RawUrl);
    }
  }

EnsureHttpAttribute

  public class EnsureHttpAttribute : FilterAttribute, IAuthorizationFilter
  {
    public void OnAuthorization(AuthorizationContext filterContext)
    {
      Verify.NotNull(filterContext, "filterContext");
      Verify.True(filterContext.HttpContext.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase), "filterContext");

      var request = filterContext.HttpContext.Request;
      if (request.Url != null && request.IsSecureConnection)
        filterContext.Result = new RedirectResult("http://" + request.Url.Host + request.RawUrl);
    }
  }

Almost the same implementation as RequireHttpsAttribute if memory serves; although the above implementation checks if it is a Local request and ignores the switch to HTTPS.

Upvotes: 7

Related Questions