【问题标题】:How can I remove the output cache on a per-user basis in ASP.NET MVC?如何在 ASP.NET MVC 中按用户删除输出缓存?
【发布时间】:2011-07-08 08:44:36
【问题描述】:

我正在使用VaryByCustom 在每个浏览器和每个用户的基础上创建一个输出缓存:

[OutputCache(Duration = 6000, VaryByParam = "*", VaryByCustom="browser;userName")]

(我已经覆盖了GetVaryByCustomString() 来完成这项工作。)

如果可能,我需要能够删除单个用户的输出缓存,而不会使不同用户的输出缓存失效。我读过关于HttpResponse.RemoveOutputCacheItem() 的文章,但是可以通过删除基于路径的输出缓存来实现。有什么方法可以根据 VaryByCustom 字符串做到这一点?

【问题讨论】:

    标签: c# asp.net-mvc caching asp.net-mvc-3


    【解决方案1】:

    为什么不在参数中包含用户,然后通过 VaryByParam 将每个用户都包含在内。

    【讨论】:

    • 可以,但我不想添加其他不必要的查询字符串参数。
    【解决方案2】:

    也许使用

    Response.Cache.SetVaryByCustom(string custom);
    

    在 ActionFilter 中,您可以构建包含浏览器版本和用户的字符串

    【讨论】:

    • 这基本上就是我已经在做的事情。我需要的是能够为用户重置缓存,即使他们使用的是同一个浏览器。
    【解决方案3】:

    您可以通过覆盖HttpApplication.GetVaryByCustomString 并检查HttpContext.Current.User.IsAuthenticated. 来利用[OutputCache] 中的VaryByCustom 属性

    这是我将在 Global.asax.cs 文件中创建的内容:

    public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (custom == "UserName")
            {
                if (context.Request.IsAuthenticated)
                {
                    return context.User.Identity.Name;
                }
                return null;
            }
    
            return base.GetVaryByCustomString(context, custom);
        }
    

    然后在OutputCache属性中使用:

    [OutputCache(Duration = 10, VaryByParam = "none", VaryByCustom = "UserName")]
    public ActionResult Profiles()
    {
        //...
    }
    

    但请注意,在这种情况下,用户名应该是不可变的!

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2010-09-27
      • 1970-01-01
      • 2020-09-02
      相关资源
      最近更新 更多