MVC3 Razor - 即将到期的页面

kol*_*uri 9 asp.net razor asp.net-mvc-3

我需要使我的内容过期,以便当用户点击浏览器导航(后退)按钮时,控制器操作将被执行.因此,不是将以下代码添加到每个
操作,而是更好的方法.

HttpContext.Response.Expires = -1;
HttpContext.Response.Cache.SetNoServerCaching();
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();
Run Code Online (Sandbox Code Playgroud)

Swa*_*aff 28

您可以将此逻辑放入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();

        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}
Run Code Online (Sandbox Code Playgroud)