2012-01-27 3 views
1

Я создал метод WCF Webservice, который получает два параметра, строку и возвращает XmlElement.Jquery Ajax и WCF Webservice nightmare

У меня есть страница ASP.NET с вызовом JQuery AJAX для этого метода. Он не работает, и онлайн-документация просто меня смущает. Некоторые аспекты, которые следует иметь в виду, это то, что прямо сейчас мы отправляем параметры в кодировке url.

Я бы не прочь в этот момент сделать все это в JSON. Мне просто нужно заставить это работать.

Мой веб-сервис отлично работает, когда я использую клиент тестирования WCF (Visual Studio 2010). Но я просто не могу заставить JQuery AJAX поговорить с ним. Я получаю ошибку «Плохой запрос».

Если вам нужна дополнительная информация, не стесняйтесь спрашивать.

Вот мой WSDL для WebService:

<?xml version="1.0" encoding="UTF-8"?> 
<wsdl:definitions xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" 
     xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" 
     xmlns:wsa10="http://www.w3.org/2005/08/addressing" 
     xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" 
     xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" 
     xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" 
     xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" 
     xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" 
     xmlns:tns="http://tempuri.org/" 
     xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 
     xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
     xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
     xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
     targetNamespace="http://tempuri.org/" 
     name="AddressVerification"> 
    <wsdl:types> 
    <xsd:schema targetNamespace="http://tempuri.org/Imports"> 
     <xsd:import namespace="http://tempuri.org/" 
      schemaLocation="http://localhost:16859/AddressVerification.svc?xsd=xsd0"/> 
     <xsd:import namespace="http://schemas.microsoft.com/2003/10/Serialization/" 
      schemaLocation="http://localhost:16859/AddressVerification.svc?xsd=xsd1"/> 
    </xsd:schema> 
    </wsdl:types> 
    <wsdl:message name="IAddressVerification_DoWork_InputMessage"> 
    <wsdl:part name="parameters" element="tns:DoWork"/> 
    </wsdl:message> 
    <wsdl:message name="IAddressVerification_DoWork_OutputMessage"> 
    <wsdl:part name="parameters" element="tns:DoWorkResponse"/> 
    </wsdl:message> 
    <wsdl:message name="IAddressVerification_VerifyAddress_InputMessage"> 
    <wsdl:part name="parameters" element="tns:VerifyAddress"/> 
    </wsdl:message> 
    <wsdl:message name="IAddressVerification_VerifyAddress_OutputMessage"> 
    <wsdl:part name="parameters" element="tns:VerifyAddressResponse"/> 
    </wsdl:message> 
    <wsdl:portType name="IAddressVerification"> 
    <wsdl:operation name="DoWork"> 
     <wsdl:input message="tns:IAddressVerification_DoWork_InputMessage" 
      wsaw:Action="http://tempuri.org/IAddressVerification/DoWork"/> 
     <wsdl:output message="tns:IAddressVerification_DoWork_OutputMessage" 
      wsaw:Action="http://tempuri.org/IAddressVerification/DoWorkResponse"/> 
    </wsdl:operation> 
    <wsdl:operation name="VerifyAddress"> 
     <wsdl:input message="tns:IAddressVerification_VerifyAddress_InputMessage" 
      wsaw:Action="http://tempuri.org/IAddressVerification/VerifyAddress"/> 
     <wsdl:output message="tns:IAddressVerification_VerifyAddress_OutputMessage" 
      wsaw:Action="http://tempuri.org/IAddressVerification/VerifyAddressResponse"/> 
    </wsdl:operation> 
    </wsdl:portType> 
    <wsdl:binding name="BasicHttpBinding_IAddressVerification" 
     type="tns:IAddressVerification"> 
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/> 
    <wsdl:operation name="DoWork"> 
     <soap:operation style="document" 
      soapAction="http://tempuri.org/IAddressVerification/DoWork"/> 
     <wsdl:input> 
     <soap:body use="literal"/> 
     </wsdl:input> 
     <wsdl:output> 
     <soap:body use="literal"/> 
     </wsdl:output> 
    </wsdl:operation> 
    <wsdl:operation name="VerifyAddress"> 
     <soap:operation style="document" 
      soapAction="http://tempuri.org/IAddressVerification/VerifyAddress"/> 
     <wsdl:input> 
     <soap:body use="literal"/> 
     </wsdl:input> 
     <wsdl:output> 
     <soap:body use="literal"/> 
     </wsdl:output> 
    </wsdl:operation> 
    </wsdl:binding> 
    <wsdl:service name="AddressVerification"> 
    <wsdl:port name="BasicHttpBinding_IAddressVerification" 
      binding="tns:BasicHttpBinding_IAddressVerification"> 
     <soap:address location="http://localhost:16859/AddressVerification.svc"/> 
    </wsdl:port> 
    </wsdl:service> 
</wsdl:definitions> 

Вот мой JQuery:

$(document).ready(function() { 

    $("#btnSubmit").click(function (e) { 
     e.preventDefault(); 
     var address1 = $("#txtAddress1").val(); 
     var address2 = $("#txtAddress2").val(); 
     var city = $("#txtCity").val(); 
     var state = $("#txtState").val(); 
     var zipcode = $("#txtZipcode").val(); 

     var dataToSend = "address=" + address1 + "&city=" + city + "&state=" + state + "&zip=" + zipcode; 

     $.ajax(
     { 
      method: "POST", 
      url: "http://localhost:16859/AddressVerification.svc/AddressVerification", 
      data: dataToSend, 
      success: function (dataReturned) { 
       alert("YAY!!!!!!!"); 
      }, 
      error: function (dataReturned, status, errorT) { 
       alert('error thrown: ' + errorT); 
       alert('status: ' + status); 
       alert('dataReturned: ' + dataReturned.toString()); 
      }, 
      cache: false 
     }); 
    }); 
}); 

Вот мой web.config

<?xml version="1.0"?> 
<configuration> 

    <system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="ServiceBehavior"> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     <behavior> 
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
      <serviceMetadata httpGetEnabled="true"/> 
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="EndpBehavior"> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <services> 
     <service behaviorConfiguration="ServiceBehavior" name="Service"> 
     <endpoint address="" binding="webHttpBinding" 
      contract="IAddressVerification" behaviorConfiguration="EndpBehavior"/> 
     </service> 
    </services> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 

</configuration> 

ответ

0

Какие привязок ваши WCF конечные точки настроен на использование?

Глядя на ваш WSDL, похоже, вы используете привязку, которая использует SOAP - это не сработает с тем, как вы пытаетесь отправить свои данные через jQuery.

Посмотрите на использование webHttpBinding. Это позволит службе реагировать на простые веб-запросы.

http://msdn.microsoft.com/en-us/library/bb412176.aspx

EDIT: Вы также хотите украсить свой AddressVerification OperationContract со следующим атрибутом:

[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    ResponseFormat = WebMessageFormat.Json, 
    UriTemplate = "AddressVerification ")] 

Это выставит метод по адресу «HTTP: // локальный: 16859/AddressVerification.svc/AddressVerification "и вернуть ответ JSON.

+0

Hello Rocco !!! Я добавил к исходному вопросу мой web.config. Я думаю, что я правильно настроен. Как вы думаете? –

+0

Это выглядит правильно. Какие атрибуты у вас есть в вашем сервисе 'OperationContract'? См. Мое редактирование. – RoccoC5

+0

Rocco !!! Моя вина. У меня был мой метод jquery: «POST» вместо типа: «Post» .... :(Idiot Code of the Day –