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