0
votes

I would like to call a WCF service with an Ajax call but it returns me a 404 Error Not found error

The url is accessible through the browser and the port 1506 is open

This is my Ajax call : I would like to use POST type

$.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 side

IService1.cs Here, I added, the POST method [ServiceContract] public interface 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
404 means the url which are using for post request can not be contacted by ajax call.It means resource not found.Monitor the reuqest either with chrome debugger tool(F12) networking tab/fiddler/postman.Also looking at your ajax call where is your object which are you sending?Navoneel Talukdar

2 Answers

1
votes

Do some testing with a tool to validade your problem. I usually use Postman. It allows you to construct the POST message and test it against your endpoint, that's the best way for you to the determine the actual cause of the problem.

0
votes

I found a solution and now it works In this case, don't forget the port 3070 into the firewall settings

If you want to access your service from an another computer, you may change your applicationhost.xml file

IService1.cs Here, I added the ResponseFormat (JSON), the RequestFormat (JSON), the UriTemplate to access my function via the 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 No changes here

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 Here, I added services tag with endpointBehaviors to add webHttp tag inside

    <?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 side No major changes here

$.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);
                }
       }
    });