3

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

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

当我导航到该页面时,正如预期的那样,我被重定向到 HTTPS。

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

似乎 OutputCache 忽略了 HTTPS,从而允许对页面进行不安全的访问。甚至可以缓存通过 HTTPS 提供的操作吗?

4

1 回答 1

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();
}
于 2011-04-09T11:47:12.423 回答