无法通过ajax调用访问服务器中托管的Wcf服务,但可以访问本地计算机中托管的相同Wcf服务

时间:2013-12-03 07:23:22

标签: wcf rest

创建了一个Wcf Restful服务并托管在本地服务器中。另一个用户试图通过ajax调用从HTML5页面使用WCF Rest服务。但总是抛出失败的消息

配置设置:

1. WCF Rest服务托管在http://jtl_109.com/mob/AppService.svc/GetUserAuthendication   2.处理HTML5应用程序并将其部署在另一台服务器上。网址为http://jtl_110.com/SampleApplication.html

  

WCF托管配置设置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <add key="ConnectionString" value="Data Source=ServerDatabase; Initial Catalog=NewDataBase; User ID=pras; Password=rita" />

  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
        <authentication mode="Windows" />
        <roleManager enabled="true" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="crossDomain" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="tSeyvaWCFEndPointBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="tSeyvaServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="AppServices.AppService" behaviorConfiguration="tSeyvaServiceBehavior">
        <endpoint address="" behaviorConfiguration="tSeyvaWCFEndPointBehavior" 
                  bindingConfiguration="crossDomain" binding="webHttpBinding" 

        contract="AppServices.IAppService">
        </endpoint>
      </service>
    </services>
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true" />
    <handlers accessPolicy="Read, Execute, Script" />
  </system.webServer>

</configuration>
  

ajax调用是

        var data = { 'logindetails': { 'UserName': UN, 'Password': PW } };
        var st = JSON.stringify(data);
        debugger;
        $.ajax({
            type: "POST",
            url: "http://jtl_109/mob/AppService.svc/GetUserAuthendication",
            data: st,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                ServiceSucceeded(result);
                //// Play with response returned in JSON format
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR + "-" + textStatus + "-" + errorThrown);
            }


        });

任何人都可以建议如何从其他网站使用WCF重置服务吗?

1 个答案:

答案 0 :(得分:0)

检查服务器上的端口是否未被防火墙阻止。一种简单的方法是只需在本地机器的浏览器地址栏中键入Web服务的URL - http:// ServerName:8001 / ServiceClass / ServiceMethod

如果您收到404错误或类似错误,请检查防火墙设置(入站)以查看该端口是否已打开。但是,如果您在浏览器中得到了良好的响应,那么您就知道它不是防火墙。

好的,所以这是一个非常简单的htm / JavaScript程序,我写作测试工具来ping WCF Web服务。

 <title>SOAP JavaScript Client Test</title>     
 <script type="text/javascript">

 function Ping() {             
 //set up varable
 var sContent;
 sContent=  "<SoapXML><Your Content></XML>";

 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', Demo.URL.value, true);  

 xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) {
    //alert("Ready state: " + xmlhttp.readyState.toString());
    if (xmlhttp.status == 200) {
        //alert("good");
        Demo.pingresponse.value = "Response: " +xmlhttp.responseText;
    }
    if (xmlhttp.status !=200){
        //alert("bad");
        Demo.pingresponse.value = "Error: " +xmlhttp.status.toString() +"  response text:  " +xmlhttp.responseText;
    }
} else {
    //alert("readystate bad");
}
 }

    //send request    

xmlhttp.setRequestHeader("POST http:localhost:8085/ServiceName  HTTP/1.1"); 
xmlhttp.setRequestHeader("VsDebuggerCausalityData","uI8ACQAA"); 
xmlhttp.setRequestHeader("SOAPAction","\"http://SoapRequestHeader\""); 
xmlhttp.setRequestHeader("Host","localhost:8085"); 
xmlhttp.setRequestHeader("Expect","100-continue"); 
xmlhttp.setRequestHeader("Accept-Encoding","gzip, deflate"); 
xmlhttp.setRequestHeader("Connection","Keep-Alive"); 
xmlhttp.setRequestHeader("Content-Length","639");                   
xmlhttp.setRequestHeader("Content-type", "text/xml; charset=utf-8"); 
xmlhttp.send(sContent);                  
 }

</script> 
</head> 
<body>     
<form name="Demo" action="" method="post">         
<div>
Web Service URL (i.e. http://ServerName:8085/ServiceName <br />
<input id="URL" type="text" size="140" value="http:/ /localhost:8085/ServiceName " />
<br />             
<input type="button" value="Ping" onclick="Ping();" /><br />
<textarea id="pingresponse"cols="100" rows="10">
</textarea> <br />     
</div>     
</form> 
</body> 
<html> 

显然,这不适用于您的网站,但通过对网址,端口和预期内容进行一些调整,这可能是一个很好的起点。