Fork me on GitHub

ASP.NET 页面禁止被 iframe 框架引用

两个站点:

  • a.sample.com
  • b.sample.com

a.sample.com 站点中的一段示例 JS 代码:

var iframe = document.createElement("iframe");
iframe.id = "frame";
iframe.src="http://b.sample.com/index.html";
iframe.onload = function() {
   var domdoc = iframe.contentDocument || iframe.contentWindow.document;
   domdoc.write("Test");
   alert("..or..")
   domdoc.body.innerHTML = "<em>Cake</em>";    
}
document.body.appendChild(iframe);

如果 b.sample.com 站点禁止被 a.sample.com 站点 iframe 框架引用,需要在 a.sample.com 站点中配置请求头 X-Frame-Options

  • DENY(禁止被任何站点引用): The page cannot be displayed in a frame, regardless of the site attempting to do so.
  • SAMEORIGIN(只能被本站点引用): The page can only be displayed in a frame on the same origin as the page itself.

ASP.NET MVC 站点设置方法:

1. Html.BeginForm

@Html.AntiForgeryToken()//默认设置为 SAMEORIGIN。

2. Application_Start

protected void Application_Start()
{
    AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
}

3. web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="X-Frame-Options" value="DENY" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

4. IIS 站点设置

posted @ 2015-08-11 18:26  田园里的蟋蟀  阅读(3250)  评论(0编辑  收藏  举报