【问题标题】:.NET MVC add custom headers to all 302 responses.NET MVC 向所有 302 响应添加自定义标头
【发布时间】:2019-02-26 16:42:40
【问题描述】:

我目前有一个 mvc 应用程序,它位于一个安全的第三方网关后面。此网关正在缓存 302 响应,这在某些情况下会导致我的应用程序中加载屏幕的无限循环。我试图找到一种将自定义标头添加到响应中的方法,但仅适用于 302,因为我从不希望它们被缓存,但是我的应用程序确实需要缓存其他状态代码的资源。我知道我可以使用:

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

但是,这将为所有响应设置缓存标头,而不仅仅是 302。我怎样才能实现相同的行为,但仅适用于 302 重定向?

我也尝试为它创建一个自定义过滤器,如下所示:

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

并在Global.asax注册:

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

但是这似乎没有任何效果。请注意,这是一个 Sitefinity MVC 应用程序。

【问题讨论】:

    标签: .net asp.net-mvc iis sitefinity


    【解决方案1】:

    看起来 web.config 的 &lt;httpProtocol&gt; 部分支持仅影响名为 &lt;redirectHeaders&gt; 的重定向的部分。有关文档,请参阅 here。解决我的问题的示例用法如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-06
      • 2012-11-09
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2012-10-27
      相关资源
      最近更新 更多