2012-04-10 26 views
7

Llamo (Ajax Request) a un servicio WCF REST y la solicitud es una solicitud de dominio cruzado.Cross Domain jQuery Ajax Request y WCF REST Service

Si despliego mi servicio en el mismo dominio, todo funciona como crema. Eventualmente en producción, el servicio estará en un dominio diferente.

Estoy usando jQuery 1.5.2. Mi servicio me devuelve un error diciendo:

errorThrown: "jQuery15208493315000087023_1334089616458 was not called" 
textStatus: "parsererror" 

Aunque en Firefox puedo ver los valores JSON pero la ejecución cae al gestor de errores de la petición Ajax. CrossDomainScriptAccess

function CallService() { 
    $.ajax({ 
     type: "GET", 
     url: "http://SomeService/EmpService.svc/GetValues?dv=1455", 
     contentType: "application/json; charset=utf-8", 
     dataType: "jsonp", 
     processdata: false,    
     success: function (data) { 
      ServiceSucceeded(data); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      debugger; 
      alert("Service Error"); 
      ServiceFailed(jqXHR, textStatus, errorThrown); 
     } 
    }); 
} 

lado servicio WCF, He configurado como true::

Mi petición Ajax es

<webHttpBinding> 
    <binding name="webHttpBindingWithJsonP" 
      crossDomainScriptAccessEnabled="true" /> 
</webHttpBinding> 

respuesta JSON, que llego del servidor es:

[{"Message": "Stop On Duty", "MessageTime": "\/Date(1334068773893-0500)\/"}, 
{"Message": "Start On Duty", "MessageTime": "\/Date(1334068763540-0500)\/"}, 
{"Message": "App_testing_4102012924am", "MessageTime": "\/Date(1334068533627-0500)\/"}, 
{"Message": "Kunal_testing_4102012924am", "MessageTime": "\/Date(1334067945510-0500)\/"}, 
{"Message": "Alert: Door Open", "MessageTime": "\/Date(1334066280963-0500)\/"}] 

Me falta algo aquí en la configuración. Todo el código funciona bien si el servicio se mueve al mismo dominio.

Miré en una publicación similar pero no pude hacer esto.

+0

espero que también haya agregado archivo de política entre dominios, marque aquí http://msdn.microsoft.com/en-us/library/cc197955%28v = vs.95% 29.aspx – Chandermani

+0

sí, eso ya está allí en la raíz –

Respuesta

5

Bueno, lo descubrí por mi cuenta. Solución fue modificar el archivo de configuración de la celebración de los detalles del servicio

añadí estándar de punto final y la unión en el archivo de configuración

<standardEndpoints> 
     <webScriptEndpoint> 
     <standardEndpoint crossDomainScriptAccessEnabled="true"> 
     </standardEndpoint> 
     </webScriptEndpoint> 
     </standardEndpoints> 



    <bindings> 

    <webHttpBinding> 
    <binding name="webHttpBindingWithJsonP" 
      crossDomainScriptAccessEnabled="true" /> 
    </webHttpBinding> 
+6

a qué sección de su web.config agregó esto? –

+0

@ matthew_360 bajo la etiqueta que está debajo de la etiqueta padre

+0

¿Cómo podemos también especificar dominios específicos en la configuración para permitir el acceso "Cross Domain"? – Virus

2

que tenía que añadir también <webHttpEndpoint> para conseguir que funcione:

<standardEndpoints> 
    <webHttpEndpoint> 
     <standardEndpoint crossDomainScriptAccessEnabled="true"></standardEndpoint> 
    </webHttpEndpoint> 
    <webScriptEndpoint> 
     <standardEndpoint crossDomainScriptAccessEnabled="true"></standardEndpoint> 
    </webScriptEndpoint> 
</standardEndpoints> 

<bindings> 
    <webHttpBinding> 
     <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" /> 
    </webHttpBinding> 
</bindings> 
+0

Aprecio su formateo más limpio –

0
[OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, RequestFormat=WebMessageFormat.Json, 
    UriTemplate = "GetEmployeeJson")] 
    List<EmployeeData> GetEmployeeJson(); 

Web.config

<bindings> 
     <webHttpBinding> 
      <binding name="webHttpBindingWithJsonP" 
        crossDomainScriptAccessEnabled="true" /> 
     </webHttpBinding> 
    </bindings> 
    <behaviors> 
     <serviceBehaviors> 
      <behavior name="WcfExample.Service1Behavior"> 
       <serviceMetadata httpGetEnabled="true"/> 
       <serviceDebug includeExceptionDetailInFaults="true"/> 
      </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
      <behavior name="WebBehavior"> 
       <webHttp/> 
      </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <services> 
     <service behaviorConfiguration="WcfExample.Service1Behavior" name="WcfExample.Service1"> 
      <endpoint address="" binding="webHttpBinding" contract="WcfExample.IService1" bindingConfiguration="webHttpBindingWithJsonP" behaviorConfiguration="WebBehavior" /> 
     </service> 
    </services> 

jQuery Ajax llamada al servicio WCF

$.ajax({ 
      type: "GET", 
      contentType: "application/javascript", 
      crossDomain: true, 
      dataType: 'jsonp', 
      cache: true, 
      url: 'http://localhost:49349/Service1.svc/GetEmployeeJson', 
      success: function (data) { 
       var html = []; 

       alert(data[0].lastname); 


       $.each(data, function (index, value) { 
        $("#TableID").append("<tr><td>" + value.HREmpId + "</td><td>" + value.firstName + "</td><td>" + value.lastname + "</td><td>" + value.address + "</td><td>" + value.city + "</td></tr>"); 

       }); 


      }, 

      error: function (xhr, ajaxOptions, thrownError) { 
       alert("here error"); 
       alert(thrownError); 
       if (xhr != null) { 

        var err = JSON.parse(xhr.responseText); //you can throw a code-behinde Exception and it will automatically             //render to a valid JSON string when we rerieve the responseText 
        alert("ErrorMessage: " + err.Message + " StackTrace: " + err.StackTrace); 

       } 
      } 
     }); 
Cuestiones relacionadas