简体   繁体   中英

Javascript Cross Domain WCF Self Hosted Restrictions

I have a somewhat unique problem. I have a static HTML and Javascript page that needs to make calls from Javascript to a web service. This WCF web service will be self hosted as a Windows Service on a separate server. I'm running into issues when trying to communicate between the javascript page and the web service, due to Cross-Domain restrictions. I've seen a few examples on how to get around this, but since my web page is going to be static and not served from IIS I'm not sure how to go about it.

I've attached some of my code below. Any help would be appreciated.

App.Config

<?xml version="1.0"?>
<configuration>

  <configSections>
  </configSections>
  <connectionStrings>
    <add name="test.XKORE.MobileDeviceServices.Properties.Settings.ConnectionString"
      connectionString="Data Source=tester;Initial Catalog=test;User ID=testc;Password=testp" />
  </connectionStrings>
  <system.web>
    <compilation debug="true"/>
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="test.XKORE.MobileDeviceServices.XKOREMobileService" behaviorConfiguration="XKOREMobileServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8523/test/XKORE/XKOREMobileService" />
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="test.XKORE.MobileDeviceServices.IXKOREMobileService" bindingNamespace="http://test.XKORE.MobileDeviceServices" />
        <endpoint address="mex" binding="mexHttpBinding" contract="test.XKORE.MobileDeviceServices.IXKOREMobileService" bindingNamespace="http://test.XKORE.MobileDeviceServices" />

      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="XKOREMobileServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

Interface

[ServiceContract]
    public interface IXKOREMobileService
    {
        [OperationContract]
        string GetChartData();

        // TODO: Add your service operations here
    }

SOAP Request

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IXKOREMobileService/GetChartData</Action>
  </s:Header>
  <s:Body>
    <GetChartData xmlns="http://tempuri.org/" />
  </s:Body>
</s:Envelope>

Javascript (Not Working)

var response = BuildSOAPMessage('GetChartData');
alert(response);

function BuildSOAPMessage (func) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "http://localhost:8523/test/XKORE/XKOREMobileService", false);

    var msg = '';
    msg += '<?xml version="1.0" encoding="utf-8"?>'
    msg += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">'
    msg += '<soapenv:Header/>'
    msg += '<soapenv:Body>'
    msg += '<tem:' + func + '/>'
    msg += '</soapenv:Body>'
    msg += '</soapenv:Envelope>'
    alert (msg);

     // Send the POST request
     xmlhttp.setRequestHeader('Content-Type', 'text/xml');
     xmlhttp.setRequestHeader("SOAPAction", "http://tempuri.org/IXKOREMobileService/GetJSONChartData");
     xmlhttp.send(msg);

    return xmlhttp.responseXML;
}

Your problem is not unique... It's the call to your WS that's failing because of CORS.

So you have to set the HTTP header 'Access-Control-Allow-Origin' in your WS by implementing an IDispatchMessageInspector :

public void BeforeSendReply(ref Message reply, object correlationState)
{
    var httpResponse = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
    if (httpResponse != null)
    {
        //CORS
        httpResponse.Headers["Access-Control-Allow-Origin"] = "*";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM