覆盖IIS响应标头

时间:2017-09-22 13:41:37

标签: c# asp.net iis

由于我在同一个IIS实例上托管了多个网站,因此我定义了HTTP响应标头' X-Frame-Options:DENY'在IIS设置中,以确保我的客户(及其客户)免受点击劫持。

我目前正在电子商务网站上使用WebForms,我需要删除' X-Frame-Options'特定网址上的响应标头(我的支付提供商的回调)。

我已经编写了一个HTTP模块(请参阅下面的代码)并将其注册在' web.config'我的电子商务网站,代码工作,但似乎IIS在执行我的HttpModule后添加了响应头。

public class XFrameOptionsControl : IHttpModule
{
  public void Dispose()
  {
  }

  public void Init(HttpApplication application)
  {
    application.PreSendRequestHeaders += new EventHandler(PreSendRequestHeaders);
  }

  private void PreSendRequestHeaders(object sender, EventArgs e)
  {
    HttpApplication application = sender as HttpApplication;
    HttpContext context = application.Context;

    string callbackDocumentName = "callback.html";

    if (callbackDocumentName != null)
    {
      if (!context.Request.RawUrl.ToLower().Contains(callbackDocumentName.ToLower()))
      {
        context.Response.Headers.Remove("X-Frame-Options");
      }
    }
  }
}

通常,' callbackDocumentName'是从' web.config'中检索的,但我确实为示例简化了它。我尝试使用Visual Studio和' context.Response.Headers'进行调试。包含以下标题,但不包含' X-Frame-Options':

  • CacheControl
  • 内容类型
  • 服务器
  • X-ASPNET-版

提前致谢!

1 个答案:

答案 0 :(得分:0)

如果要更改响应,则需要在生成响应后执行此操作。

目前您甚至在请求发送到您的应用程序之前就已经完成了

试试这个

        public void Init(HttpApplication context)
        {
            context.PostRequestHandlerExecute += new EventHandler(this.ProcessResponse);
        }

        private void ProcessResponse(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            //do whatever you want to the context
            //context.Response.Headers.Remove
            }
        }