MVC3 Razor - 过期页面

10

我需要使我的内容过期,这样当用户点击浏览器的导航(后退)按钮时,控制器操作会被执行。所以,有没有更好的方法来完成这个任务,而不是在每个操作中都添加以下代码。

HttpContext.Response.Expires = -1;
HttpContext.Response.Cache.SetNoServerCaching();
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
3个回答

29
你可以将这个逻辑放进一个ActionFilter中,这意味着你不需要在每个控制器的动作方法中添加以上代码,而是可以通过自定义过滤器来修饰Action方法。或者,如果它适用于控制器中的所有Action方法,你可以将属性应用于整个控制器。
你的ActionFilter应该像下面这样:
public class MyExpirePageActionFilterAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            filterContext.HttpContext.Response.Expires = -1;
            filterContext.HttpContext.Response.Cache.SetNoServerCaching();
            filterContext.HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
            filterContext.HttpContext.Response.CacheControl = "no-cache";
            filterContext.HttpContext.Response.Cache.SetNoStore();

        }
    }

查看这篇文章了解更多信息。

如果您想在整个应用程序的所有操作上应用此设置,实际上可以在Global.asax中设置全局ActionFilter,将ActionFilter应用于所有操作:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    GlobalFilters.Filters.Add(new MyExpirePageActionFilterAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

是的,我同意我需要创建一个ActionFilter。而且我正在创建这个过程中。所以根据您的回答,我想这种方法已经得到了验证。我希望能得到有关该过滤器内部的反馈。我拥有的5行代码是否合理或是否有更好的方法?谢谢。 - kolhapuri
@kolhapuri 我明白了,看看这个链接,其中有人想要防止Safari缓存上一页的内容。 - Swaff
今天遇到了这个问题,但是找到了解决方法! - Don Zacharias

1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接