ASP.NET MVC:OutputCache属性忽略RequireHttps属性?

时间:2011-04-08 08:18:46

标签: asp.net-mvc asp.net-mvc-3 outputcache requirehttps

我有一个ASP.NET MVC 3应用程序,其动作同时使用RequireHttpsOutputCache属性:

[RequireHttps]
[OutputCache(Duration = 14400, VaryByCustom = "CurrentUser"]
public ActionResult VersionB()
{
  return View();
}

当我导航到该页面时,我会按预期重定向到HTTPS。

然而,在初始页面加载之后,我仍然可以通过HTTP访问页面。如果我删除OutputCache属性,则无法再通过HTTP访问该页面。

似乎OutputCache忽略了HTTPS,因此允许对页面进行不安全的访问。是否可以缓存通过HTTPS提供的操作?

1 个答案:

答案 0 :(得分:10)

[RequireHttps]属性实现存在缺陷,并未考虑缓存。

这是一个修复:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class MyRequireHttpsAttribute : RequireHttpsAttribute
{
    protected virtual bool AuthorizeCore(HttpContextBase httpContext)
    {
        return httpContext.Request.IsSecureConnection;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!AuthorizeCore(filterContext.HttpContext))
        {
            this.HandleNonHttpsRequest(filterContext);
        }
        else
        {
            var cache = filterContext.HttpContext.Response.Cache;
            cache.SetProxyMaxAge(new TimeSpan(0L));
            cache.AddValidationCallback(this.CacheValidateHandler, null);
        }
    }

    private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
    }

    protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext)
    {
        if (!AuthorizeCore(httpContext))
        {
            return HttpValidationStatus.IgnoreThisRequest;
        }
        return HttpValidationStatus.Valid;
    }
}

然后:

[MyRequireHttps]
[OutputCache(Duration = 14400, VaryByCustom = "CurrentUser"]
public ActionResult VersionB()
{
    return View();
}