使用javascript SOAP请求使用WCF服务

时间:2013-04-22 10:53:54

标签: javascript wcf cordova soap

我有一个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. 

我知道这是一个跨域错误,但这就是为什么将以下方法添加到我的webservice的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请求?

1 个答案:

答案 0 :(得分:0)

这看起来像老问题。你已经解决了吗? 如果没有,你可以将实际请求发送到服务器吗?尝试用Fiddler捕获它。