【问题标题】:MVC3 Razor - Expiring pagesMVC3 Razor - 即将过期的页面
【发布时间】:2011-03-18 13:47:36
【问题描述】:

我需要使我的内容过期,这样当用户点击浏览器的导航(返回)按钮时,控制器操作就会被执行。因此,不要将以下代码添加到每个
行动有没有更好的方法来做到这一点。

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

【问题讨论】:

    标签: asp.net asp.net-mvc-3 razor


    【解决方案1】:

    您可以将此逻辑放入 ActionFilter 中,这意味着无需将上述代码添加到控制器中的每个 Action 方法中,您只需使用自定义过滤器装饰 Action 方法即可。或者,如果它适用于 Controller 中的所有 Action 方法,您可以将该属性应用到整个 Controller。

    您的 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();
    
            }
        }
    

    有关更多信息,请参阅this 文章。

    如果您希望在整个应用程序的所有 Actions 上都这样做,您实际上可以使用 Global.asax 中设置的全局 ActionFilter 将 ActionFilter 应用于所有 Actions:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        GlobalFilters.Filters.Add(new MyExpirePageActionFilterAttribute());
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
    

    【讨论】:

    • 是的,我同意我需要创建一个 ActionFilter。我正在创造它。所以我想这种方法是根据你的回答得到验证的。我想要反馈的是剧院过滤器内部的内容。我所说的 5 行是否有意义或有更好的方法吗?谢谢。
    • @kolhapuri 我明白了,看看这个link here,它描述了有人想要阻止 Safari 缓存上一页。
    • 今天遇到了这个问题,它解决了我遇到的问题!
    【解决方案2】:

    您可以编写自己的ActionFilter 并将代码放入其中。

    如果你不想用这个过滤器装饰你所有的动作方法,那么你可以将它注册为一个全局动作过滤器:http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx

    【讨论】:

      【解决方案3】:

      你可以把它放在HTTP Module中。

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        相关资源
        最近更新 更多