[RequireHttps]之后的MVC3如何确保使用非https

时间:2012-01-24 19:28:24

标签: c# asp.net-mvc-3 https annotations

我找到了This Post,它看起来就像我需要的应用程序,我的问题是,当不再需要https时,如何恢复为纯http?它是否会根据没有[RequireHttps]注释的动作而固有地执行此操作?

编辑:我发现有几篇帖子谈论从https转到http(here& here)。但是,我仍然对以下问题的答案表示赞赏。

或者,我一直在讨论如何在新窗口中打开应用程序。 https只适用于新窗口是公平的假设吗?

2 个答案:

答案 0 :(得分:7)

ASP.NET MVC的RequireHttps只有一种方式。在过去,我刚刚创建了自己的FilterAttribute实现,允许双向旅行:

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

如果内存服务,几乎与RequireHttpsAttribute相同;虽然上述实现检查它是否是Local请求并忽略切换到HTTPS。

答案 1 :(得分:2)