2009-08-12 14 views
17

Tengo una aplicación consola de cliente hablando con un servicio WCF y me sale el siguiente error: "El servidor no dio una respuesta significativa, lo que podría ser causado por un desajuste contrato, un cierre de sesión prematuro o un error interno del servidor ".WCF contrato desajuste problema

Creo que es por una falta de coincidencia de contrato, pero no puedo entender por qué. El servicio funciona bien por sí mismo y las 2 partes funcionaron juntas hasta que agregué el código de suplantación.

¿Alguien puede ver lo que está mal?

Aquí es el cliente, todo hecho en código:

NetTcpBinding binding = new NetTcpBinding(); 
binding.Security.Mode = SecurityMode.Message; 
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows; 

EndpointAddress endPoint = new EndpointAddress(new Uri("net.tcp://serverName:9990/TestService1")); 
ChannelFactory<IService1> channel = new ChannelFactory<IService1>(binding, endPoint); 
channel.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; 
IService1 service = channel.CreateChannel(); 

y aquí está el archivo de configuración del servicio WCF:

<configuration> 
    <system.serviceModel> 
    <bindings> 
     <netTcpBinding> 
     <binding name="MyBinding"> 
      <security mode="Message"> 
      <transport clientCredentialType="Windows"/> 
      <message clientCredentialType="Windows" /> 
      </security> 
     </binding> 
     </netTcpBinding> 
    </bindings> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior name="WCFTest.ConsoleHost2.Service1Behavior"> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
      <serviceAuthorization impersonateCallerForAllOperations="true" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <services> 
     <service behaviorConfiguration="WCFTest.ConsoleHost2.Service1Behavior" 
      name="WCFTest.ConsoleHost2.Service1"> 
     <endpoint address="" binding="wsHttpBinding" contract="WCFTest.ConsoleHost2.IService1"> 
      <identity> 
      <dns value="" /> 
      </identity> 
     </endpoint> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
     <endpoint binding="netTcpBinding" bindingConfiguration="MyBinding" 
      contract="WCFTest.ConsoleHost2.IService1" /> 
     <host> 
      <baseAddresses> 
      <add baseAddress="http://serverName:9999/TestService1/" /> 
      <add baseAddress="net.tcp://serverName:9990/TestService1/" /> 
      </baseAddresses> 
     </host> 
     </service> 
    </services> 
    </system.serviceModel> 
</configuration> 

Respuesta

1

Ok, acabo de modificar el cliente por lo que utiliza un archivo de configuración en lugar de código y me sale el mismo error!

Código:

ServiceReference1.Service1Client client = new WCFTest.ConsoleClient.ServiceReference1.Service1Client("NetTcpBinding_IService1");  
client.PrintMessage("Hello!"); 

Aquí está el archivo de configuración del cliente, recién generado del servicio ... lo que hace que mi pensar que tal vez no sea un error de falta de coincidencia contrato

<configuration> 
    <system.serviceModel> 
     <bindings> 
      <netTcpBinding> 
       <binding name="NetTcpBinding_IService1" closeTimeout="00:01:00" 
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" 
        transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" 
        hostNameComparisonMode="StrongWildcard" listenBacklog="10" 
        maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10" 
        maxReceivedMessageSize="65536"> 
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" 
         maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
        <reliableSession ordered="true" inactivityTimeout="00:10:00" 
         enabled="false" /> 
        <security mode="Message"> 
         <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" /> 
         <message clientCredentialType="Windows" /> 
        </security> 
       </binding> 
      </netTcpBinding> 
      <wsHttpBinding> 
       <binding name="WSHttpBinding_IService1" closeTimeout="00:01:00" 
        openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" 
        bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" 
        maxBufferPoolSize="524288" maxReceivedMessageSize="65536" 
        messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" 
        allowCookies="false"> 
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" 
         maxBytesPerRead="4096" maxNameTableCharCount="16384" /> 
        <reliableSession ordered="true" inactivityTimeout="00:10:00" 
         enabled="false" /> 
        <security mode="Message"> 
         <transport clientCredentialType="Windows" proxyCredentialType="None" 
          realm="" /> 
         <message clientCredentialType="Windows" negotiateServiceCredential="true" 
          algorithmSuite="Default" establishSecurityContext="true" /> 
        </security> 
       </binding> 
      </wsHttpBinding> 
     </bindings> 
     <client> 
      <endpoint address="http://servername:9999/TestService1/" binding="wsHttpBinding" 
       bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1" 
       name="WSHttpBinding_IService1"> 
       <identity> 
        <dns value="&#xD;&#xA;   " /> 
       </identity> 
      </endpoint> 
      <endpoint address="net.tcp://serverName:9990/TestService1/" binding="netTcpBinding" 
       bindingConfiguration="NetTcpBinding_IService1" contract="ServiceReference1.IService1" 
       name="NetTcpBinding_IService1"> 
       <identity> 
        <userPrincipalName value="MyUserPrincipalName " /> 
       </identity> 
      </endpoint> 
     </client> 
    </system.serviceModel> 
</configuration> 
+0

Sí, probablemente no - el mensaje de error también ofrece dos más casuse posible:" ....., un cierre de sesión prematuro o una error de servidor interno." –

33

Otras causas posibles:

  • Tratando de serializar un obj ect sin un constructor predeterminado.
  • Intentando serializar algún otro tipo de objeto no serializable (como una excepción). Para evitar que el artículo se serialice, aplique el atributo [IgnoreDataMember] al campo o a la propiedad.
  • Comprueba tus campos de enumeración para asegurarte de que están configurados con un valor válido (o pueden contener nulos). Es posible que deba agregar un valor de 0 a la enumeración en algunos casos. (no estoy seguro acerca de los detalles de este punto).

Qué prueba:

  • Configure WCF tracing de errores críticos o al menos excepciones. Tenga cuidado de ver el tamaño del archivo si habilita cualquier rastro adicional. Esto proporcionará información muy útil en muchos casos.

    Solo agregue esto debajo de <configuration> en su web.configEN EL SERVIDOR. Cree el directorio log si no existe.

<system.diagnostics> 
    <sources> 
     <source name="System.ServiceModel" 
       switchValue="Error, Critical" 
       propagateActivity="true"> 
     <listeners> 
      <add name="traceListener" 
       type="System.Diagnostics.XmlWriterTraceListener" 
       initializeData= "c:\log\WCF_Errors.svclog" /> 
     </listeners> 
     </source> 
    </sources> 
    </system.diagnostics> 
  • Asegúrese de que el archivo .svc realidad se van a plantear en un navegador sin error. Esto te dará una ayuda 'de primera oportunidad'. Por ejemplo, si tiene un objeto no serializable, recibirá este mensaje a continuación. Tenga en cuenta que claramente le dice lo que no se puede serializar. Asegúrese de tener habilitado el punto final 'mex' y haga que aparezca el archivo .svc en su navegador.

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: http://tempuri.org/:IOrderPipelineService ----> System.Runtime.Serialization.InvalidDataContractException: Type 'RR.MVCServices.PipelineStepResponse' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.

+2

+1 Gracias - Me impactó este error, encontré tu respuesta, y resultó que el problema fue causado por una enumeración de máscara de bits: cuando tienes más de un bit configurado (y por lo tanto ningún valor enum que coincida) la serialización ¡falla! –

+0

Tengo un problema similar. El servicio esta bien. Un cliente está trabajando; pero el segundo cliente no funciona: http://stackoverflow.com/questions/12420314/one-wcf-service-two-clients-one-client-does-not-work – Lijo

8

Para mí, este mensaje de error se produce porque el comportamiento de mi servicio web.config por defecto tiene un límite de mensajes baja, así que cuando el WCF regresó decir 200000 bytes y mi límite era de 64000 bytes, la respuesta fue truncado y así obtienes la "... respuesta no significativa". Es significativo, simplemente se truncó y no se puede analizar.

Pegaré mi cambio web.config que ha solucionado el problema:

<system.serviceModel> 
<behaviors> 
<serviceBehaviors> 
<behavior name="YourNameSpace.DataServiceBehavior"> 
<serviceMetadata httpGetEnabled="true"/> 
<serviceDebug includeExceptionDetailInFaults="false"/> 
     <dataContractSerializer maxItemsInObjectGraph="2147483647" /> 
     <serviceTimeouts transactionTimeout="05:05:00" /> 
     <serviceThrottling maxConcurrentCalls="500" maxConcurrentSessions="500" 
     maxConcurrentInstances="2147483647" /> 
</behavior> 
</serviceBehaviors> 
</behaviors> 

El valor maxItemsInObjectGraph es el más importante!
Espero que esto ayude a cualquiera.

+0

Tengo un problema similar. El servicio esta bien. Un cliente está trabajando; pero el segundo cliente no funciona: http://stackoverflow.com/questions/12420314/one-wcf-service-two-clients-one-client-does-not-work – Lijo

0

Si tiene dos métodos con el mismo nombre y los parámetros en su WCF que arrojará este error

2

que estaba teniendo un problema similar. Después de pensar dos horas en esto e intentar encontrar una respuesta en línea, decidí seguir el enfoque para separar y deserializar el valor/objeto de retorno en el lado del servidor utilizando System.Runtime.Serialization.DataContractSerializer y finalmente encontré que había fallado al agregar el atributo EnumMember en uno de los Enumeraciones.

Es posible que se encuentre con un problema similar.

Aquí es el fragmento de código que me ayudó a resolver el problema:

 var dataContractSerializer = new System.Runtime.Serialization.DataContractSerializer(typeof(MyObject)); 
     byte[] serializedBytes; 
     using (System.IO.MemoryStream mem1 = new System.IO.MemoryStream()) 
     { 
      dataContractSerializer.WriteObject(mem1, results); 
      serializedBytes = mem1.ToArray(); 
     } 

     MyObject deserializedResult; 
     using (System.IO.MemoryStream mem2 = new System.IO.MemoryStream(serializedBytes)) 
     { 
      deserializedResult = (MyObject)dataContractSerializer.ReadObject(mem2); 
     } 
+0

Esta fue la opción más rápida para la depuración local, gracias ! –

Cuestiones relacionadas