JQuery 找不到 WCF 服务/404(未找到)

JQuery can't find WCF service / 404 (Not Found)

我在 VS2010 中使用 WCF vb.net。我需要从 jQuery.

调用 WCF 服务方法

我有这项服务:(CustomerSearch.svc)

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

我有这个界面:(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

这是我的实现:(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

这是我的 html 页面的一部分:

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

我可以在我的浏览器中浏览我的服务

我收到这个错误:

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

这是我的一部分 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>

我该如何解决这个错误?

我认为您的服务是正确的,只需在您定义服务 class:

的位置添加 [Serializable] 属性
[Serializable]
Public Class CustomerSearch

其次,如果您确定您的 WCF 地址没问题,请按此更改您的 Jquery 代码: 从此改变:

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

对此:

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

所以我认为在您的 webconfig 中,在行为点需要更改此代码:

  <webHttp />

最后,在您的测试之后,我建议在您的 jQuery 代码中单独添加此配置:

 $.ajax({
           cache: false,
           async: false,
        //    type: "Post",
        //   url: "http://localhost/.../....svc/GetCustomer",
           contentType: "application/json",
           dataType: "json",

我找到了我的解决方案:

我只是在 SVC 文件中添加 Factory 属性。

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

我改变了我的 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>

之后成功了!