如何在ASP.NET MVC中基于每个用户删除输出缓存?

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

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

(我已经重写了GetVaryByCustomString()以使其工作。)

我需要能够删除单个用户的输出缓存,如果可能的话,不会使不同用户的输出缓存失效。 我已经阅读了HttpResponse.RemoveOutputCacheItem() ,但这可以通过删除基于路径的输出缓存来实现。 有没有办法根据VaryByCustom字符串执行此操作?

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

这是我将在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() { //... } 

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

为什么不让用户参与参数,然后通过VaryByParam为每个用户。

也许用

 Response.Cache.SetVaryByCustom(string custom); 

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