asp.net – MVC3 Razor – 到期页面

我需要使我的内容过期,以便当用户点击浏览器导航(返回)按钮时,控制器动作被执行.所以不是每个都添加以下代码
行动是有更好的方式来做到这一点.
HttpContext.Response.Expires = -1;
HttpContext.Response.Cache.SetNoServerCaching();
Response.Cache.SetAllowResponseInBrowserHistory(false);
Response.CacheControl = "no-cache";
Response.Cache.SetNoStore();

解决方法

您可以将此逻辑放入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文章.

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

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

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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....