4

我有一个 MVC4 应用程序。WebPageRequireHttpsAttribute在我的基本控制器上,当我不在 DEBUG 中时,我有一个条件重定向来保护所有其他页面服务控制器继承如下:

#if !DEBUG
    [WebPageRequireHttps]
#endif
    public abstract class SecureController : Controller
    {
        ...

WebPageRequireHttpsAttribute的定义如下:

[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
    Justification = "Unsealed because type contains virtual extensibility points.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class WebPageRequireHttpsAttribute : 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)
    {
        // only redirect for GET requests, otherwise the browser might not propagate the verb and request
        // body correctly.

        if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException(
                "Only redirect for GET requests, otherwise the browser might not propagate the verb and request body correctly.");
        }

        // redirect to HTTPS version of page
        if (filterContext.HttpContext.Request.Url == null) return;
        var url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
        filterContext.Result = new RedirectResult(url, true);
    }

而已。这是对网页进行重定向的唯一点(我对 webapi 页面有类似的东西)。

让我的站点处于 DEBUG 模式,并设置了 DEBUG 常量,我被重定向到 HTTPS 页面,这当然在我的开发框中不存在,我绝对不知道为什么。我已经注释掉了这个属性,我什至删除了这个类,它仍然被重定向。我在这里拉头发。

IIS Express 可以缓存一些奇怪的东西吗?是否可以将重定向属性应用为所有请求的过滤器,而不管它是否被调用?这真让我抓狂。

4

2 回答 2

12

好的,答案与 Visual Studio、C# 或 ASP.NET MVC 无关……而是我的默认浏览器,即 Chrome。我发送了一个 301(永久重定向),Chrome 缓存了它。在正常情况下,这将是一件好事;对于开发工作,没有那么多。

要从 Chrome 中删除缓存的重定向,我打开了 Chrome 选项,设置,单击“显示高级设置”。在隐私下,我单击了“清除浏览数据...”按钮,并检查了以下选项:

  • 清除浏览记录
  • 清除下载历史
  • 删除 cookie 和其他网站和插件数据
  • 清空缓存

并将下拉时间段设置为 1 周。然后我再次单击“清除浏览数据”按钮。

我很确定我只需要其中一个选项,但是我对使用霰弹枪方法的这个烦人的问题感到非常沮丧。然而,这奏效了。

于 2013-07-02T11:39:53.847 回答
-1

全球.asax.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new RequireHttpsAttribute()); // <----
}

我已经在许多使用这种方法的应用程序中强制使用 HTTPS/SSL。

就这样吧,希望对你有帮助。

于 2013-06-30T16:22:37.190 回答