首页  >  文章  >  web前端  >  如何在 IIS7 上启用跨域资源共享 (CORS)?

如何在 IIS7 上启用跨域资源共享 (CORS)?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-26 04:39:02972浏览

How to Enable Cross-Origin Resource Sharing (CORS) on IIS7?

在 IIS7 上启用跨源资源共享 (CORS)

跨源资源共享 (CORS) 允许 Web 应用程序在不同源上运行相互发出 HTTP 请求。但是,默认情况下,不允许向其他域发送 XHR 请求。

在目标域上启用 CORS

要在目标域上启用 CORS,请添加以下自定义web.config 文件的标头:

<code class="xml"><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" /
        <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" /
        <add name="Access-Control-Allow-Headers" value="Content-Type" /
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration></code>

IIS7 配置

在目标域上启用 CORS 后,您可能仍会遇到 405 Method Not allowed 响应。这可能是由于 IIS7 处理 HTTP OPTIONS 响应而不是您的应用程序。

要解决此问题:

  1. 导航到 IIS7 中站点的处理程序映射。
  2. 找到“OPTIONSVerbHandler”映射。
  3. 将“ProtocolSupportModule”更改为“IsapiHandler”。
  4. 将可执行文件设置为“%windir%Microsoft.NETFrameworkv4.0.30319aspnet_isapi.dll”。

或者,在代码中响应 HTTP OPTIONS

您还可以在 BeginRequest 方法中响应 HTTP OPTIONS 动词:

<code class="csharp">    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            // Pre-flight OPTIONS call
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }</code>

以上是如何在 IIS7 上启用跨域资源共享 (CORS)?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn