如何在ASP.NET MVC中按用户删除输出缓存? [英] How can I remove the output cache on a per-user basis in ASP.NET MVC?

查看:83
本文介绍了如何在ASP.NET MVC中按用户删除输出缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using VaryByCustom to create an output cache on a per-browser and per-user basis:

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

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

(I've overridden GetVaryByCustomString() to make this work.)

如果可能的话,我需要能够删除单个用户的输出缓存,而不会使其他用户的输出缓存无效.我已经读过关于HttpResponse.RemoveOutputCacheItem()的内容,但这可以通过删除基于路径的输出缓存来实现.有什么办法可以基于VaryByCustom字符串执行此操作吗?

I need to be able to remove a single user's output cache, without invalidating the output cache of different users, if possible. I've read about HttpResponse.RemoveOutputCacheItem(), but that works by removing the output cache based on path. Is there any way to do this based on the VaryByCustom string?

推荐答案

您可以通过覆盖HttpApplication.GetVaryByCustomString并检查HttpContext.Current.User.IsAuthenticated.

You can take the advantage of VaryByCustom property in [OutputCache] by overriding HttpApplication.GetVaryByCustomString and check HttpContext.Current.User.IsAuthenticated.

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

This is what I will create in Global.asax.cs file:

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属性中使用它:

And then use it in OutputCache attribute:

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

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

but be careful that the username should be immutable in this case!

这篇关于如何在ASP.NET MVC中按用户删除输出缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆