0

I am using WCF in VS2010 with vb.net. I need call a WCF service method from jQuery.

I have this service: (CustomerSearch.svc)

<%@ ServiceHost Language="VB" Debug="true" Service="CustomerSearch" 
    CodeBehind="~/App_Code/Classes/Customer/CustomerSearch.vb" %> 

And I have this interface: (ICustomerSearch)

Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Runtime.Serialization

<ServiceContract()>
Public Interface ICustomerSearch

    <OperationContract()>
    <System.ServiceModel.Web.WebInvoke(Method:="POST", _
        ResponseFormat:=System.ServiceModel.Web.WebMessageFormat.Json)> _
    Function GetCustomer(ByVal CustomerSearch As String) As String

End Interface

This is my implementation: (CustomerSearch)

Imports System.ServiceModel.Activation
Imports System.Data
Imports System.ServiceModel
Imports System.ServiceModel.Web
Imports System.Web.Script.Serialization

<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class CustomerSearch
    Implements ICustomerSearch

    <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
    Public Function GetCustomer(ByVal CustomerSearch As String) As String Implements ICustomerSearch.GetCustomer

        Dim customers As New List(Of Object)()
        Dim objSqlWrapper As New CADatabase.SqlWrapper
        Dim objRsCustomer As System.Data.DataSet

        ...... 
        Return (New JavaScriptSerializer().Serialize(customers))

    End Function

End Class

This is one part of my html page :

 $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/WCF/Reservauto/Customers/CustomerSearch.svc/GetCustomer",
    data: '{"CustomerSearch": "' + $("#CustomerNameSearch").val() + '"}',
    processData: false,
    dataType: "json",
    success: function(data) {
        strListStations = $( 'Station', data ).map(function() {
            return {
                value: $(this).attr('StationNo') + ' - ' + $(this).text(),
                id: new google.maps.LatLng($(this).attr('Latitude'), $(this).attr('Longitude')),
                latitude: $(this).attr('Latitude'),
                longitude: $(this).attr('Longitude')
            };
        }).get();

        $('#CustomerNameSearch').autocomplete({
            source: strListStations,
            minLength: 2,
            select: function(event, ui) {

                $('#CustomerStationID').val('');
                $('#MapAddress').val('');
            }
        }).autocomplete("widget").addClass("fixed-height");
    },
    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);
        }
    }
});

I can browse my service in my browser

enter image description here

I got this error :

POST https://www.dev.reservauto.net/WCF/Reservauto/Customers/CustomerSearch.svc/GetCustomer 404 (Not Found)

 m.ajaxTransport.send @ jquery.min.js:4
 m.extend.ajax @ jquery.min.js:4
 (anonymous function) @ AbonneDossier.asp:107
 m.Callbacks.j @ jquery.min.js:2
 m.Callbacks.k.fireWith @ jquery.min.js:2
 m.extend.ready @ jquery.min.js:2J @ jquery.min.js:2

this is one part of my Web.config

<system.serviceModel>

<behaviors>

  <serviceBehaviors>    
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>

  <!--ASP.Net AJAX endpoint behaviour to enable AJAX calls to the service.-->
  <endpointBehaviors>
    <behavior name="ServiceAspNetAjaxBehavior">
      <enableWebScript/>
      <!--<webHttp/>-->
    </behavior>
  </endpointBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

<!--Declare that our service use endpointBehaviors-->
<services>
  <service name="CustomerSearch" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="webHttpBinding" contract="CustomerSearch" behaviorConfiguration="ServiceAspNetAjaxBehavior">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
</services>

<bindings>

How can I fix this error?

Ardalan Shahgholi
  • 11,967
  • 21
  • 108
  • 144

2 Answers2

1

I think your service is true just add [Serializable] attribute where you defined Service class:

[Serializable]
Public Class CustomerSearch

Second, change your Jquery code by this if you sure your WCF address is OK: Changing from this :

url: "/WCF/Reservauto/Customers/CustomerSearch.svc/GetCustomer",
data: '{"CustomerSearch": "' + $("#CustomerNameSearch").val() + '"}',

to this:

data: JSON.stringify({CustomerSearch: $("#CustomerNameSearch").val()});

So I think in your webconfig, at Behavior point needs to change this code:

  <webHttp />

Finally after your tests, I recommend that adding this configuration individually in your jQuery code :

 $.ajax({
           cache: false,
           async: false,
        //    type: "Post",
        //   url: "http://localhost/.../....svc/GetCustomer",
           contentType: "application/json",
           dataType: "json",
Harry Sarshogh
  • 2,137
  • 3
  • 25
  • 48
0

I found my solution:

I just add Factory attribute in SVC file.

<%@ ServiceHost 
            Language="VB" 
            Debug="true" 
            Service="CustomerSearchService" 
            CodeBehind="~/App_Code/Classes/Customer/CustomerSearchService.vb" 
            Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"%> 

And I changed my web.Config

  <behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="EndpBehavior">
      <webHttp/>
        <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="CustomerSearchService">
    <endpoint address="" binding="webHttpBinding" contract="ICustomerSearchService" behaviorConfiguration="EndpBehavior"/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>


</services>

After that it worked!

Ardalan Shahgholi
  • 11,967
  • 21
  • 108
  • 144