MVC3 Razor - Expiring pages

2019-02-02 15:41发布

问题:

I need to expire my content so that when the user hits the browsers navigation(back) button the controller action gets executed. So instead of adding the following code to each and every
action is there a better way to do it.

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

回答1:

You can put this logic into an ActionFilter meaning that rather than adding the above code to each of your Action methods in your controller, you can just decorate the Action method with your custom filter. Or if it applies to all Action methods in a Controller you can apply the attribute to the whole Controller.

Your ActionFilter will be something like this:

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();

        }
    }

See this article for more information.

If you want this on all Actions of your entire application, you can actually apply an ActionFilter to all Actions using a global ActionFilter set up in your Global.asax:

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

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

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


回答2:

You can write your own ActionFilter and put the code in there.

If you don't want to decorate all of your action methods with this filter, then you can register it as a global action filter: http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx



回答3:

You could put it in an HTTP Module.