我正在尝试通过在如下所示的 Web 服务方法中启用“Access-Control-Allow-Origin”标头来添加 CORS 设置。但是,我仍然收到错误:请求的资源上不存在“Access-Control-Allow-Origin”标头。我错过了什么吗?
[ScriptMethod(UseHttpGet = true)]
[WebMethod]
public ClientData[] GetClientData(int Number)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:52630");
ClientData[] Clients = null;
if (Number > 0 && Number <= 10)
{
Clients = new ClientData[Number];
for (int i = 0; i < Number; i++)
{
Clients[i].Name = "Client " + i.ToString();
Clients[i].ID = i;
}
}
return Clients;
}
将其放入您的 web.config 中
您可以根据需要进行调整。这个例子我只打开.aspx
<configuration>
<system.web>
<httpHandlers>
<add verb="GET,HEAD,POST,OPTIONS" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
</httpHandlers>
</system.web>
</configuration>
您可能也需要这样的东西。
if (Request.HttpMethod == "OPTIONS")
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("Access-Control-Allow-Headers", "Content-Type");
return;
}
将其添加到您的 Web.config 文件中:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin"
value="*" />
<add name="Access-Control-Allow-Credentials"
value="true" />
<add name="Access-Control-Allow-Headers"
value="SOAPAction, Content-Type,Authorization" />
<add name="Access-Control-Allow-Methods"
value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
有关详细信息,请检查https://www.codeproject.com/Questions/827596/Cross-domain-SOAP-call-with-XmlHttpRequest-to-a-we