我有一个 WCF 服务,我必须使用 JavaScript SOAP 请求来使用它。JavaScript 是 Phonegap 应用程序的一部分,因此我不是从本地服务器而是从文件运行此 JavaScript。
当 WCF 服务运行 localhost 时,一切正常。但是,一旦我在服务器上部署 WCF 服务,就会收到错误消息(服务名称及其方法仅用于说明目的):
OPTIONS http://myWebservice/service.svc 400 (Bad Request)
XMLHttpRequest cannot load http://myWebservice/service.svc. Origin null is not allowed by Access-Control-Allow-Origin.
我知道这是一个跨域错误,但这就是为什么将以下方法添加到我的 web 服务的 global.asax 中。但这无济于事。
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept,SOAPAction");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
javascript调用:
$.support.cors = true;
var bodyrequest = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<s:Body>" +
"<"getAll xmlns=\"http://tempuri.org/\" />" +
"</s:Body>" +
"</s:Envelope>";
return $.ajax({
type: "POST",
//This works
//url: "http://localhost:49704/myWebservice/service.svc",
//this doesn't work
url: "http://myWebservice/service.svc",
data: bodyrequest,
timeout: 10000,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://tempuri.org/service/getAll ");
},
});
wcf 服务的 web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="myWebservice/service">
<endpoint address="" binding="basicHttpBinding" contract="Contract.myWebservice"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<appSettings>
...
</appSettings>
有人有想法吗?还是有其他方法可以对 WCF 服务进行跨域 SOAP Javascript 请求?