JQuery无法找到WCF服务/ 404(未找到)

时间:2015-04-27 16:42:38

标签: jquery vb.net visual-studio-2010 wcf

我在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);
        }
    }
});

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

enter image description here

我收到了这个错误:

  

POST https://www.dev.reservauto.net/WCF/Reservauto/Customers/CustomerSearch.svc/GetCustomer 404(未找到)

 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>

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

我认为您的服务属实,只需在您定义服务类的位置添加 [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",

答案 1 :(得分:0)

我找到了解决方案:

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

<%@ 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>

之后它起作用了!