WCF communication error - c#

We've been encountering a WCF communication error for a couple of days now and I can't figure out what is causing the error. I originally thought that it was an SSL cert issue, but it's not. I also made sure the endpoint was reachable by just entering the URL on the web browser and it is view-able. I also made sure that the default request size is not causing the problem. I'm certain that the requests are less than the default of 30MB.
What other things can prevent this stack trace error?
Client stack trace:
WCFDirector fetch failed due to communication failure.
Because the form did not load properly it must be closed. ---> OSI.Framework.FrameworkException: WCFDirector fetch failed due to communication failure. ---> System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Try to set KeepAlive off.
Something like:
var client = new MyWcfClient();
var customBinding = new CustomBinding(client.Endpoint.Binding);
var transportElement = customBinding.Elements.Find<HttpTransportBindingElement>();
transportElement.KeepAliveEnabled = false;
client.Endpoint.Binding = customBinding;
Config only version for Rest API and SOAP
<services>
<service name="SecureTransportDemo.Service.GreetingService">
<endpoint address="Soap"
binding="customBinding"
bindingConfiguration="soap-secure-nokeepalive"
contract="SecureTransportDemo.Service.IGreetingService"
name="soap-nokeepalive"/>
<endpoint address="Rest"
binding="customBinding"
bindingConfiguration="rest-secure-nokeepalive"
behaviorConfiguration="web"
contract="SecureTransportDemo.Service.IGreetingService"
name="rest-nokeepalive"/>
</service>
</services>
<bindings>
<customBinding>
<binding name="soap-secure-nokeepalive">
<textMessageEncoding />
<httpsTransport allowCookies="false"
keepAliveEnabled="false"/>
</binding>
<binding name="rest-secure-nokeepalive">
<webMessageEncoding />
<httpsTransport manualAddressing="true"
allowCookies="false"
keepAliveEnabled="false"/>
</binding>
</customBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp automaticFormatSelectionEnabled="true"
faultExceptionEnabled="true"
helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>

Related

WCF REST 400 Bad Request Error [duplicate]

I am using a RestClient app to communicate with my WCF service .and I am getting the following exception
The underlying connection was closed: An unexpected error occurred on a receive.
This is the C# code I use
string q = string.Format(#"xxxxxxxxxxxxxxxxxxxxxxxxxxx");
WebClient client = new WebClient();
string Url = string.Format("{0}/Get?queries={1}", BaseUrl,HttpUtility.UrlEncodeUnicode(q));
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var result = client.DownloadString(Url);
Console.WriteLine("======================output================================");
Console.WriteLine(result);
Console.WriteLine("===========================================");
Here is the error message
System.Net.WebException was caught
HResult=-2146233079
Message=The underlying connection was closed: An unexpected error occurred on a receive.
Source=System
StackTrace:
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at RestClient.Program.GetRecordsTest() in C:\Users\Wiemon\Downloads\RestAppClient\RestAppClient\Program.cs:line 118
InnerException: System.IO.IOException
HResult=-2146232800
Message=Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Source=System
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
InnerException: System.Net.Sockets.SocketException
HResult=-2147467259
Message=An existing connection was forcibly closed by the remote host
Source=System
ErrorCode=10054
NativeErrorCode=10054
StackTrace:
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
InnerException:
Here is my binding
<binding name="wsHttpEndpoint" >
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport">
<transport clientCredentialType="Certificate" />
<message clientCredentialType="Certificate" />
</security>
</binding>
And my endpoint behavior ,not that I set maxItemsInObjectGraph="2147483647"
<behavior name="MyEndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<clientCredentials>
<clientCertificate findValue="xxxxxxxxxxxxxxxxxx" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
<serviceCertificate>
<authentication certificateValidationMode="None" revocationMode="NoCheck" />
</serviceCertificate>
</clientCredentials>
</behavior>
Its common (generic) message.
You should use Trace Viewer Tool (SvcTraceViewer.exe) to find out server error
I had similar errors coming from the depths of my http bindings in WCF.
client -> The underlying connection was closed: An unexpected error occurred on a receive.
client -> Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
server (got this with the help of "procdump") -> The I/O operation has been aborted because of either a thread exit or an application request
Eventually after many hours I came upon the HTTP.sys logging (in C:\WINDOWS\System32\LogFiles\HTTPERR ) and I discovered that the WCF self-hosted service connections were being forcibly dropped (on purpose) because of an obscure configuration issue (minimum send rate bytes per second). Unfortunately it took another few hours to reconfigure that (you cannot do it via "netsh http add timeout" so you have to do it within the app or within IIS when not self-hosted).
I dont't know if is the same error, but in my case, the exception was in Json, that cannot convert the Date value, because it was empty.
DateTime values that are greater than DateTime.MaxValue or smaller than DateTime.MinValue when converted to UTC cannot be serialized to JSON.
The trace viewer was very useful to find the issue.
Configure WCF tracing in your app.config / web.config and check Error.svclog (it will be created near your binary file) for details.
In my case it was because of using Auto-property initializer (property without setter) - a feature from C# 6.0
<Message>No set method for property 'FailedCount' in type 'MyProject.Contracts.Data.SyncStatusByVersion'.</Message>
<StackTrace> at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
at WriteSyncStatusByVersionToJson(XmlWriterDelegator , Object , XmlObjectSerializerWriteContextComplexJson , ClassDataContract , XmlDictionaryString[] )
...
</StackTrace>
To configure WCF tracing:
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true" >
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="xml"/>
</listeners>
</source>
<source name="myUserTraceSource" switchValue="Information, ActivityTracing">
<listeners>
<add name="xml"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="xml" type="System.Diagnostics.XmlWriterTraceListener" initializeData="Error.svclog" />
</sharedListeners>
</system.diagnostics>

WCF: The socket connection was aborted. A receive timeout being exceeded by the remote host

I have been working through a head-scratcher with WCF. I have a WCF Service (hosted as a Windows Service) that is called by a console application. It works great, but recently we have run into a timeout issue at 10 minutes when we had to run a query against a legacy system.
I use log4net in both the service and the client .exe, and what is strange is that the service actually completes the job and throws no exception. It runs the query (which takes about 12 minutes, and creates a file, and logs success).
The console application, however, logs an exception, claiming that the "host" returned a timeout or an error. I presume it's a timeout and not a buffer issue, because the exception always happens exactly 10 minutes to the second after the call is initially made.
Here is the exception/stack info from my log4net:
2015-07-28 17:35:47,364 [1]
System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:29:59.9843999'. ---> System.IO.IOException: The read operation failed, see inner exception. ---> System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:29:59.9843999'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)
--- End of inner exception stack trace ---
at System.ServiceModel.Channels.SocketConnection.ReadCore(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout, Boolean closing)
at System.ServiceModel.Channels.SocketConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.DelegatingConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security.NegotiateStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
--- End of inner exception stack trace ---
at System.Net.Security.NegotiateStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.NegotiateStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.StreamConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.SessionConnectionReader.Receive(TimeSpan timeout)
at System.ServiceModel.Channels.SynchronizedMessageSource.Receive(TimeSpan timeout)
at System.ServiceModel.Channels.TransportDuplexSessionChannel.Receive(TimeSpan timeout)
at System.ServiceModel.Channels.TransportDuplexSessionChannel.TryReceive(TimeSpan timeout, Message& message)
at System.ServiceModel.Dispatcher.DuplexChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at FileGeneratorConsole.FileGeneratorServiceReference.IFileGeneratorService.GenerateXmlFileFromSql(String sqlServer, String sqlDatabase, String sqlQuery, Int32 commandTimeout, Boolean allowEmptyResult, String outputFileName, String xslFileName, Boolean archiveExistingFile)
at FileGeneratorConsole.Program.Main(String[] args)
Now, I thought I had done my research and figured out what the issue could be. I assumed it was the sendTimeout and receiveTimeout that are part of the binding definition, so I've added that:
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IFileGeneratorService"
maxBufferPoolSize="2147483647"
maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647"
receiveTimeout="00:30:00"
closeTimeout="00:30:00"
openTimeout="00:30:00"
sendTimeout="00:30:00">
</binding>
</netTcpBinding>
</bindings>
And, if you notice in the exception above, you'll see that the error says:
Local socket timeout was '00:29:59.9843999'
It used to say 00:09:59.... so it looks like that took.
I also added this to the service config file, just in case the binding needed to be on both sides, but that didn't help.
Lastly, out of desperation, I added a few other things. I tried adding timeouts to the service section:
and I tried adding
to the behavior itself.
I'm at a loss now, it always dies at 10 minutes.
Thanks in advance
It's always simpler than you think.
Sadly, what was missing all this time was the bindingConfiguration reference in the service.endpoint. All this time, the service was running assumedly using the default binding definition. I had a binding defined in my config, but had missed the part where you specify:
I had:
<endpoint address="" binding="netTcpBinding" bindingConfiguration="">
I needed:
<endpoint address="" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IFileGeneratorService">
Once that was in place, my actual service endpoint was looking at the right binding properties.

WCF throwing before sending response to client

I have a WCF service where IGameServices contains:
[ServiceContract]
public interface IGameServices
{
[OperationContract]
DtoReturnedMessage<DtoGame> GetGame(Guid gameId);
}
AdminServices contains:
public class AdminService : IGameServices
{
private readonly BoGame _boGame = new BoGame();
public DtoReturnedMessage<DtoGame> GetGame(Guid gameId)
{
return _boGame.Get(gameId);
}
}
I have that BoGame, which is a class with business logics.
My config is:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IGameServices" sendTimeout="00:05:00" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:50380/Services/Implementations/AdminService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGameServices"
contract="IGameServices" name="BasicHttpBinding_IGameServices" />
</client>
</system.serviceModel>
When I debug it step-by-step, all the business logics works properly, and throws the exception below when the response should be sent to the client.
An error occurred while receiving the HTTP response to http://localhost:50380/Services/Implementations/AdminService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IGameServices.GetGame(Guid gameId)
at GameServicesClient.GetGame(Guid gameId)
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
Inner Exception:
An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
It is weird because I have a method to save some data into the DB, in the same IGameServices, which saves normally and returns the success message as expected.
Does any one know what that can be?
I solved the problem. The error was too generic, actually. The issue was with build versions of Postsharp not matching.
I found it out by trying to open the services directly on the browser. I removed Postsharp in that project and BANG.

How to disable security on wcf service?

I've written a WCF App with the following config in the the app.config:
<system.serviceModel>
<services>
<service name="ProxyService">
<endpoint address="net.pipe://localhost/ProxyService" binding="netNamedPipeBinding" bindingConfiguration="" name="ServiceProxy" contract="IProxyService"/>
</service>
<service name="PublishSubscribeService">
<endpoint address="net.tcp://localhost/PublishSubscribeService" binding="netTcpBinding" bindingConfiguration="" name="PublishSubscribeServer" contract="IPublishSubscribeService"/>
</service>
</services>
</system.serviceModel>
And I'm having an issue with the netTcp Binding rejecting request (I've included the other service just in case it might have an effect but I don't think it does). I'm instantiating it using the following code:
private ServiceHost incomingPipeHost;
private ServiceHost incomingSubscribeHost;
incomingPipeHost = new ServiceHost(typeof(ProxyService));
incomingPipeHost.Open();
incomingSubscribeHost = new ServiceHost(typeof(PublishSubscribeService));
incomingSubscribeHost.Open();
This all works fine when I try to connect to the net.tcp service from a client running locally, and I have had this running fine on a customer site for well over a year. However, I'm now at a different customer site and when I try to connect from a remote machine I get the following exception:
System.ServiceModel.Security.SecurityNegotiationException: The server has rejected the client credentials. ---> System.Security.Authentication.InvalidCredentialException: The server has rejected the client credentials. ---> System.ComponentModel.Win32Exception: The logon attempt failed
--- End of inner exception stack trace ---
at System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartReceiveBlob(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextSend(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartReceiveBlob(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(Stream stream)
at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection& connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ....PublishSubscribeServiceLibrary.IPublishSubscribeService.Subscribe(UserData userData)
at ....PublishSubscribeServiceLibrary.PublishSubscribeClient.Subscribe(UserData userData)
at ....OnConnected()
I've tried adding the following snippet to the system.ServiceModel to disable authentication and I still get the same error:
<bindings>
<netTcpBinding>
<binding name="netTcpBindingConfig" transferMode="Buffered" maxReceivedMessageSize="5242880">
<readerQuotas maxArrayLength="5242880" />
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
What am I doing wrong? and what can I do to try and either disable authentication (which is not a requirement) or get authentication working?
You need to tell the EndPoint with the netTcpBinding to use the correct configuration (netTcpBindingConfig):
<service name="PublishSubscribeService">
<endpoint ... bindingConfiguration="netTcpBindingConfig" ... />
</service>

WCF Error while receiving the HTTP response to my service

Hi guys I created a service using WCF but when I test my services some completed successfully why some is giving me the error below. Any Idea on how to solve these ? Thanks
An error occurred while receiving the HTTP response to http://localhost:8733/PortOperation/Operator_Service/ws. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at IOperator_Service.GetAllUser(String ConnectionString)
at Operator_ServiceClient.GetAllUser(String ConnectionString)
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
Inner Exception:
An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
There are many scenarios when this type of error occurs.
First
Check that have you provided proper [DataContract] and [DataMember]? if this is not provided then this type of error occurs. You have to write [DataContract] above the class which you pass in response, and write [DataMember] above the class member which goes into the client response.
eg.
[DataContract]
class Program
{
[DataMember]
public string Example{get;set}
}
Second
Check in the response if some minvalue of Data type is passed. That means some time data member is not initialized at that time it takes the minvalue.
e.g. minValue of int is '-2147483648' so at some time it cannot be serialized and throws an error.
If you want to trace this type of error then add the following code in your server-side web.config
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData= "D:\Traces.svclog"/>
</listeners>
</source>
</sources>
</system.diagnostics>
I think it will help you.
I was able to solve the problem.
If you are using EF "code first"-approach and you want access to your data using WCF you should consider not enabling lazy loading using the "virtual" keyword in your poco-class because WCF serialization cannot serialize dynamic proxy data.

Categories

Resources