如何清除MVC应用程序中的浏览器缓存? [英] How to clear browser cache in MVC application?

查看:397
本文介绍了如何清除MVC应用程序中的浏览器缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想清除MVC应用程序中的浏览器缓存.

I want to clear the browser cache in MVC application.

我在.cshtml页面上添加了以下代码,该代码适用于IE和Firefox.

I added the below code on my .cshtml page and its working for IE and Firefox.

    Response.ExpiresAbsolute = DateTime.Now;
    Response.Expires = 0;
    Response.CacheControl = "no-cache";
    Response.Buffer = true;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.UtcNow);
    Response.Cache.SetNoStore();
    Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

我正在寻找一种适用于chrome的解决方案.

I am looking for a solution which will work on chrome as well.

推荐答案

使用以下属性:

public class NoCacheAttribute : ActionFilterAttribute
{        
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (filterContext == null) throw new ArgumentNullException("filterContext");

        var cache = GetCache(filterContext);

        cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        cache.SetValidUntilExpires(false);
        cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        cache.SetCacheability(HttpCacheability.NoCache);
        cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }

    /// <summary>
    /// Get the reponse cache
    /// </summary>
    /// <param name="filterContext"></param>
    /// <returns></returns>
    protected virtual HttpCachePolicyBase GetCache(ResultExecutingContext filterContext)
    {
        return filterContext.HttpContext.Response.Cache;
    }
 }

}

只需将其添加到您的基本控制器中即可:

Simply add this to your base controller :

[NoCache]
public BaseController: Controller

这篇关于如何清除MVC应用程序中的浏览器缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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