How can I remove the output cache on a per-user ba

2019-03-29 20:14发布

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

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

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

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?

3条回答
对你真心纯属浪费
2楼-- · 2019-03-29 20:31

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

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);
    }

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!

查看更多
Root(大扎)
3楼-- · 2019-03-29 20:33

perhaps use

Response.Cache.SetVaryByCustom(string custom);

in an ActionFilter the you can build up the string including browser version and user

查看更多
女痞
4楼-- · 2019-03-29 20:47

Why not have the user in the parameters and then it would be per-user through the VaryByParam.

查看更多
登录 后发表回答