How to disable cache of browser in asp.net mvc 3?

2020-02-11 06:14发布

问题:

I have created my custom authentication. Now I want to disable cache of broswer on log off button click. How should I do that? What should I include in log off action?

I'm following: http://www.bradygaster.com/custom-authentication-with-mvc-3.0

回答1:

Is your concern the browser back button after logging off?

If yes, then you should not disable the cache on log off. You should disable it on all pages that you don't want to be cached which in your case would be all authentciated pages.

This could be done by writing a custom action filter:

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;
        response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        response.Cache.SetValidUntilExpires(false);
        response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
    }
}

and then decorating your actions with it:

[Authorize]
[NoCache]
public ActionResult Foo()
{
    ...
}