带有WCF调用的Ajax返回404错误

时间:2016-02-15 13:52:13

标签: c# jquery ajax wcf

我想用Ajax调用调用WCF服务,但它返回404错误未找到错误

可通过浏览器访问网址,端口1506已打开

这是我的Ajax调用: 我想使用POST类型

$.ajax(
    {
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       url: "http://192.168.80.18:1506/Service1.svc/GetData",
       type: 'POST',
       success: function (data, status, xhr)
       {
           alert('Success: '+data);
       },                        
       error: function(x, e)
       {
           if (x.status == 0) {
                    alert('You are offline!!\n Please Check Your Network.');
                } else if (x.status == 404) {
                    // Here is the problem
                    alert('Requested URL not found.');
                } else if (x.status == 500) {
                    alert('Internal Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
       }
    });

WCF方

IService1.cs 在这里,我添加了POST方法     [服务合约]     公共接口IService1     {

    [OperationContract]
    [WebInvoke(Method= "POST", ResponseFormat= WebMessageFormat.Json)]
    string GetData();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: ajoutez vos opérations de service ici
}

Service1.svc

public class Service1 : IService1
{
    public string GetData()
    {
        return "Hello world!";
    }
}

的Web.config

    <?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- Pour éviter la divulgation d'informations de métadonnées, définissez les valeurs ci-dessous sur false avant le déploiement -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Pour recevoir les détails de l'exception dans les erreurs à des fins de débogage, définissez la valeur ci-dessous sur true. Pour éviter la divulgation d'informations d'exception, définissez-la sur false avant le déploiement -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="Service1.svc"
                  binding="basicHttpBinding"
                  contract="WcfService1.IService1" />
      </service>
    </services>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        Pour parcourir le répertoire racine de l'application Web lors du débogage, définissez la valeur ci-dessous sur true.
        Définissez-la sur false avant le déploiement pour ne pas divulguer d'informations du dossier de l'application Web.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

2 个答案:

答案 0 :(得分:1)

使用工具进行一些测试以验证您的问题。 我通常使用Postman。它允许您构建POST消息并针对您的端点进行测试,这是确定问题实际原因的最佳方式。

答案 1 :(得分:0)

我找到了解决方案,现在可行了 在这种情况下,请不要忘记端口3070进入防火墙设置

如果要从另一台计算机访问服务,可以更改applicationhost.xml文件

<强> IService1.cs 在这里,我添加了ResponseFormat(JSON),RequestFormat(JSON),UriTemplate来通过url访问我的函数:http://192.168.80.18:3070/Service1.svc/GetData

public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,UriTemplate="/getdata")]
    string GetData();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

<强> Service1.svc.cs 这里没有变化

public class Service1 : IService1
{
    public string GetData()
    {
        return "It works";
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

<强>的Web.config 在这里,我使用 endpointBehaviors 添加了 services 标记,以在

中添加 webHttp 标记
    <?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxUrlLength="500"/>
  </system.web>
  <system.serviceModel>
    <services>
        <service name="WcfService2.Service1">
            <!-- Service Endpoints -->
            <endpoint address="" binding="webHttpBinding" contract="WcfService2.IService1" behaviorConfiguration="webBehavior">
            </endpoint>
        </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- Pour éviter la divulgation d'informations de métadonnées, définissez les valeurs ci-dessous sur false avant le déploiement -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Pour recevoir les détails de l'exception dans les erreurs à des fins de débogage, définissez la valeur ci-dessous sur true. Pour éviter la divulgation d'informations d'exception, définissez-la sur false avant le déploiement -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        Pour parcourir le répertoire racine de l'application Web lors du débogage, définissez la valeur ci-dessous sur true.
        Définissez-la sur false avant le déploiement pour ne pas divulguer d'informations du dossier de l'application Web.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

Ajax方 这里没有重大变化

$.ajax(
    {
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       url: "http://192.168.80.18:3070/Service1.svc/GetData",
       type: 'GET',
       data: "{}",
       success: function (data, status, xhr)
       {
           alert('Success: '+data);
       },                        
       error: function(x, e)
       {
           if (x.status == 0) {
                    alert('You are offline!!\n Please Check Your Network.');
                } else if (x.status == 404) {
                    alert('Requested URL not found.');
                } else if (x.status == 500) {
                    alert('Internal Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
       }
    });
相关问题