Search code examples
.netasp.net-mvciissitefinity

.NET MVC add custom headers to all 302 responses


I currently have an mvc app which sits behind a secure, third-party gateway. This gateway is cacheing 302 responses which in some scenarios is resulting in an endless loop of loading screens in my application. Im trying to find a way to add custom headers to the response but only for 302s as I never want them cached however my application does need to cache resources of other status codes. I know I can use:

<httpProtocol> 
  <customHeaders> 
    <add name="Cache-Control" value="max-age=0, no-cache, no-store, must-revalidate" /> 
    <add name="Pragma" value="no-cache" /> 
  </customHeaders> 
</httpProtocol>

however this will set the cache headers for all responses and not only 302s. How can I achieve the same behavior but only for 302 redirects?

I've also tried creating a custom filter for it as follows:

public class CustomCacheHeaderFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if(actionExecutedContext.Response.StatusCode == System.Net.HttpStatusCode.Redirect)
        {
            actionExecutedContext.Response.Headers.Add("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
            actionExecutedContext.Response.Headers.Add("Pragma", "no-cache");
        }
    }
}

and registering in Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
    GlobalConfiguration.Configuration.Filters.Add(new CustomCacheHeaderFilter());
}

however this doesn't seem to have any effect. Note this is a Sitefinity MVC application.


Solution

  • It looks like the <httpProtocol> section of the web.config supports a section which only affects redirects named <redirectHeaders>. See here for the docs. Example usage that solved my issue is as follows:

    <httpProtocol> 
      <redirectHeaders> 
        <add name="Cache-Control" value="max-age=0, no-cache, no-store, must-revalidate" /> 
        <add name="Pragma" value="no-cache" /> 
      </redirectHeaders> 
    </httpProtocol>