gpt4 book ai didi

javascript - 在 IIS7 上启用跨域资源共享

转载 作者:IT王子 更新时间:2023-10-29 02:46:28 25 4
gpt4 key购买 nike

我最近遇到了将 Javascript 请求发布到另一个域的问题。默认情况下不允许将 XHR 发布到其他域。

按照 http://enable-cors.org/ 中的说明进行操作,我在另一个域上启用了它。

<?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>

enter image description here

现在一切正常,但是在发回有效的 200 响应之前它仍然返回 405 响应。

Request URL:http://testapi.nottherealsite.com/api/Reporting/RunReport
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:testapi.nottherealsite.com
Origin:http://test.nottherealsite.com
Referer:http://test.nottherealsite.com/Reporting
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:private
Content-Length:1565
Content-Type:text/html; charset=utf-8
Date:Tue, 18 Sep 2012 14:26:06 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

更新:2014 年 2 月 3 日

MSDN 杂志中有一篇最近更新的文章。详述 ASP.NET Web API 2 中的 CORS 支持。

http://msdn.microsoft.com/en-us/magazine/dn532203.aspx

最佳答案

这很可能是 IIS 7“处理”HTTP OPTIONS 响应而不是您的应用程序指定它的情况。要确定这一点,在 IIS7 中,

  1. 转到您网站的处理程序映射。

  2. 向下滚动到“OPTIONSVerbHandler”。

  3. 将“ProtocolSupportModule”更改为“IsapiHandler”

  4. 设置可执行文件:%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll

现在,当发送 HTTP OPTIONS 动词时,您上面的配置条目应该启动。

或者,您可以在 BeginRequest 方法中响应 HTTP OPTIONS 动词。

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

if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
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();
}

}

关于javascript - 在 IIS7 上启用跨域资源共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com