Heero Yuy
Heero Yuy

Reputation: 614

Where do I set Response.AppendHeader in ASP.NET MVC so that it adds the following headers in all pages?

Response.Cache.SetCacheability(HttpCacheability.NoCache);  // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.

Where do I set those codes so that they are added in all my pages response header?

Thanks

Upvotes: 1

Views: 2127

Answers (1)

Shyju
Shyju

Reputation: 218702

You can create an action filter and set the needed http headers to the response. You may override the OnActionExecuted and add these new headers to the Response.

public class MyCustomHeadersFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Headers.Add("Expires","0");
        filterContext.HttpContext.Response.Headers.Add("Pragma", "no-cache");

        base.OnActionExecuted(filterContext);
    }
}

If you want this for all the requests, you can register it globally.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new MyCustomHeadersFilter());
    }
}

If you want it only for one controller, you can apply on the controller level and if you need it only for a specific action method, you may apply it on the action method level.

Upvotes: 2

Related Questions