MVC 5 中的同源策略/CORS

Same origin policy / CORS in MVC 5

asp.net mvc 应用程序中的默认策略是什么?还有 CORS 和 X-Frame-Options 有什么关系?

如果我在端口上创建一个新的 MVC Web 应用程序(托管在 IIS 中),例如21232,我将 iframe 添加到索引视图,并将源设置为我的本地 IIS,例如

<iframe src="http://localhost/iisstart.htm" width="800" height="100"/>

这工作正常(即使在 Web 应用程序的不同端口上)。

如果我现在将 iframe 源更改为完全外部的内容,例如

<iframe src="http://www.google.com" width="800" height="100"/>

这现在显示一个空的 iframe。如果我查看 Chrome 开发工具(两个示例中都使用 Chrome),我会在控制台中看到一个错误

Refused to display 'https://www.google.co.uk' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

  1. 当地址位于与托管页面不同的端口时,为什么第一个 URL 有效?
  2. X-Frame-Options 与 CORS 有什么关系?我尝试将以下内容添加到我的 web.config(参见参考 enable cors in IIS

<add name="Access-Control-Allow-Origin" value="*" />

这没什么区别。看起来好像我需要将以下内容添加到 global.asax.cs

中的 Application_Start
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

X-Frame-Options 是否与 iframe 相关?

我想你把 X-Frame-Options 响应 header 和 CORS 都搞混了。

X-Frames-Options 响应 header 用于指示是否应允许浏览器加载 <iframe> 中的特定页面。另一方面,CORS 用于确定是否允许跨域使用 XMLHttpRequest(XHR)(以及其他一些东西)。

所以,是的,X-Frames-Options 仅是 <iframe>

您能够从 http://localhost/iisstart.htm 在您的 Web 应用程序 运行 中的 21232 端口加载您的页面的原因是因为没有 X-Frame-Options 响应 header 出现在回应中。您将无法 http://www.google.com 因为它的 X-Frames-Options 设置为 SAMEORIGIN。这意味着除非您的域是 google.com,否则您将无法在 <iframe>.

中加载它

您添加的Access-Control-Allow-Originheader与<iframe>无关。您无法在页面中加载 http://www.google.com