ASP.NET MVC OutputCache因*而异,因用户cookie而异

jjx*_*tra 20 c# asp.net-mvc outputcache

我有一个asp.net mvc 3项目,我有一个家庭控制器.我已使用此属性标记了我的Index操作:

[OutputCache(Location = System.Web.UI.OutputCacheLocation.Any, Duration = 120, VaryByParam = "*", VaryByCustom = "user")]
public ActionResult Index()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

根据用户自定义的变化在Global.asax.cs中处理以检查用户cookie值,以便根据用户是否登录以及他们是什么用户来更改缓存.

当我在我的Web服务器上访问此页面时,我在响应中获得了这些标头:

Cache-Control   public, max-age=120
Content-Type    text/html; charset=utf-8
Content-Encoding    gzip
Expires Sun, 20 Mar 2011 21:50:09 GMT
Last-Modified   Sun, 20 Mar 2011 21:48:09 GMT
Vary    Accept-Encoding
Date    Sun, 20 Mar 2011 21:48:09 GMT
Content-Length  3105
Run Code Online (Sandbox Code Playgroud)

蝙蝠,Vary - Accept-Encoding值看起来不对,不应该发送Vary - *而不是吗?

我也将User.Identity.Name属性呈现给此视图,我注意到即使我注销它仍将呈现用户名,直到120秒到期.

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom.Equals("user", StringComparison.OrdinalIgnoreCase))
    {
        HttpCookie cookie = context.Request.Cookies["user"];
        if (cookie != null)
        {
            return cookie.Value;
        }
    }
    return base.GetVaryByCustomString(context, custom);
}
Run Code Online (Sandbox Code Playgroud)

一直玩这个几个小时,我完全陷入困境,希望有人有个主意......

Jim*_*rts 17

通过设置dynamicCompressionBeforeCache="true"web.config中的urlCompression元素,可以让IIS在缓存之前压缩响应.这将导致Vary:*返回预期的标头.

摘自IIS配置参考,关于dynamicCompressionBeforeCache属性:

dynamicCompressionBeforeCache属性指定IIS是否将动态压缩尚未缓存的内容.当dynamicCompressionBeforeCache属性为true时,IIS会在第一次发出请求时动态压缩响应,并对内容进行排队以进行压缩.后续请求将动态提供,直到压缩响应已添加到缓存目录.将压缩响应添加到缓存目录后,缓存的响应将发送到客户端以用于后续请求.当dynamicCompressionBeforeCachefalse时,IIS将返回未压缩的响应,直到将压缩响应添加到缓存目录.