由于我在同一个 IIS 实例上托管多个网站,因此我在 IIS 设置中定义了 HTTP 响应标头“X-Frame-Options: DENY”,以确保我的客户端(及其客户端)免受点击劫持。
我目前正在电子商务网站上使用 WebForms,我需要删除特定 url 上的“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”:
提前致谢!
如果您想更改响应,您需要在响应生成后进行更改。
目前您甚至在请求发送到您的应用程序之前就已经这样做了
试试这个
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
}
}
经过很长时间的搜索,我终于明白了,你必须使用重写规则来替换某些文件中的自定义标头,并将其设置在页面的 load 或另一个 init 方法中,这里是如何设置的示例绕过所有 aspx 和 html 文件中的 CSP 标头:
<rewrite>
<outboundRules>
<rule name="Remove Content-Security-Policy Header" preCondition="IsHtmlOrAspx">
<match serverVariable="RESPONSE_Content-Security-Policy" pattern=".+" />
<action type="Rewrite" value="" />
</rule>
<preConditions>
<preCondition name="IsHtmlOrAspx">
<add input="{REQUEST_FILENAME}" pattern="\.aspx$|\.html$" />
</preCondition>
</preConditions>
</outboundRules>
</rewrite>