I have a general purpose hosting service for WCF (.net v4). It allows for multiple agents to be dropped in plug-in style with each agent having its own config file. It was written as a service since all sites will not have IIS or WAS intalled but we can specify .net v4 and our custome service.
We have had no issues with HTTP, HTTPS or TCP (without credentials). When we add, a certificate to the server it appears to start without an issue. As soon as we attempt to call the servie we get a channel fault. We wrote a small self-hosting program that uses the config file rather than programmatically creating the endpoing and it works without any issue. We can only speculate we missed a setting but cannot identify which.
The error we get is shown below. It appears that for some reason the client it trying to set up a dual-channel tcp connection which we did not configure in the host.
Protocol Type application/negotiate was sent to a service that does not support that type of upgrade.
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.ProcessUpgradeRequest(TimeoutHelper& timeoutHelper)
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ServerFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
System.ServiceModel.Channels.CommunicationObject.Open()
System.ServiceModel.Channels.ReliableChannelListener`3.HandleAcceptComplete(TInnerChannel channel)
System.ServiceModel.Channels.ReliableChannelListener`3.OnAcceptCompleted(IAsyncResult result)
System.ServiceModel.Channels.ReliableChannelListener`3.OnAcceptCompletedStatic(IAsyncResult result)
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.Diagnostics.TraceUtility.<>c__DisplayClass4.<CallbackGenerator>b__2(AsyncCallback callback, IAsyncResult result)
System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
System.ServiceModel.Channels.TcpDuplexChannelListener.System.ServiceModel.Channels.ISessionPreambleHandler.HandleServerSessionPreamble(ServerSessionPreambleConnectionReader preambleReader, ConnectionDemuxer connectionDemuxer)
System.ServiceModel.Channels.ConnectionOrientedTransportManager`1.OnHandleServerSessionPreamble(ServerSessionPreambleConnectionReader serverSessionPreambleReader, ConnectionDemuxer connectionDemuxer)
System.ServiceModel.Channels.ConnectionDemuxer.OnSessionPreambleKnown(ServerSessionPreambleConnectionReader serverSessionPreambleReader)
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.ContinueReading()
System.ServiceModel.Channels.ServerSessionPreambleConnectionReader.StartReading(Action`1 viaDelegate, TimeSpan receiveTimeout)
System.ServiceModel.Channels.ConnectionDemuxer.OnDuplexConnection(IConnection connection, Action connectionDequeuedCallback, Int64 streamPosition, Int32 offset, Int32 size, TimeSpan timeout)
System.ServiceModel.Channels.ConnectionDemuxer.OnConnectionModeKnownCore(ConnectionModeReader modeReader, Boolean isCached)
System.ServiceModel.Channels.ConnectionDemuxer.OnConnectionModeKnown(ConnectionModeReader modeReader)
System.ServiceModel.Channels.ConnectionModeReader.Complete()
System.ServiceModel.Channels.ConnectionModeReader.ReadCallback(Object state)
System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
System.ServiceModel.Channels.TracingConnection.WaitCallback(Object state)
System.ServiceModel.Channels.SocketConnection.FinishRead()
System.ServiceModel.Channels.SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
CLIENT:
<netTcpBinding>
<binding name="NetTcpEndPoint_ISolutionsDataAccessorV01" 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="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://localhost:1177/TcpService" binding="netTcpBinding"
bindingConfiguration="NetTcpEndPoint_ISolutionsDataAccessorV01"
contract="sDAL.ISolutionsDataAccessorV01" name="NetTcpEndPoint_ISolutionsDataAccessorV01">
<identity>
<userPrincipalName value="abc#xyz.com" />
</identity>
</endpoint>
</client>
</system.serviceModel>
SERVICE:
-->
<behaviors>
<serviceBehaviors>
<behavior name="SolutionsDALServiceBehavior">
<serviceCredentials>
<serviceCertificate findValue="STSTestCert"
x509FindType="FindByIssuerName" />
</serviceCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<!-- 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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
Related
Can you please help us on the below issue?
We are getting error message as "The underlying secure session has faulted before the reliable session fully completed. The reliable session was faulted."
I have provided the config settings we are using and the error message.
ERROR 2019-08-06 05:43:48,368 1789797ms ServiceProxy`1 Invoke - The underlying secure session has faulted before the reliable session fully completed. The reliable session was faulted.
Server stack trace:
at System.Runtime.InputQueue`1.WaitQueueReader.Wait(TimeSpan timeout, T& value)
at System.Runtime.InputQueue`1.Dequeue(TimeSpan timeout, T& value)
at System.ServiceModel.Channels.InputQueueChannel`1.Dequeue(TimeSpan timeout, TDisposable& item)
at System.ServiceModel.Channels.DuplexChannel.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)
We have gone through the below link but none of the solutions provided in the link worked for us.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/6e87b039-6afb-4751-8edb-15699ce305e4/error-message-the-underlying-secure-session-has-faulted-before-the-reliable-session-fully-completed?forum=wcf
We have also enabled both trace logging and failed request tracing, but none of them
provided any insights on exact issue. Can you please suggest how can we know the cause for the above issue.
Thank You.
CONFIG SETTINGS
> <behaviors>
> <serviceBehaviors>
> <behavior name="svcBehav">
> <serviceAuthorization>
> <authorizationPolicies>
> <add >
>policyType="DistributedServices.PanelManagement.Security.AuthPolicy, >DistributedServices.PanelManagement" />
> </authorizationPolicies>
> </serviceAuthorization>
> <persistenceSession />
> <customMessageInspector />
> <serviceMetadata httpGetEnabled="true" />
> <serviceDebug includeExceptionDetailInFaults="true" />
> <dataContractSerializer maxItemsInObjectGraph="2147483647" />
><serviceThrottling maxConcurrentSessions = "50"/>
> </behavior>
></serviceBehaviors>
></behaviors>
><bindings>
><customBinding>
> <binding name="netTcpCustomBindingConfig" closeTimeout="00:59:00" >openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00">
> <reliableSession ordered="true" inactivityTimeout="20:00:00" >maxPendingChannels="20" maxRetryCount="20"/>
> <windowsStreamSecurity protectionLevel="EncryptAndSign" />
> <binaryMessageEncoding>
> <readerQuotas maxDepth="32" maxStringContentLength="2147483647" >maxArrayLength="2147483647" maxBytesPerRead="2147483647" >maxNameTableCharCount="2147483647"/>
> </binaryMessageEncoding>
> <tcpTransport maxBufferPoolSize="2147483647" >maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
> portSharingEnabled="true" transferMode="Buffered" >hostNameComparisonMode="StrongWildcard" listenBacklog="10">
> <connectionPoolSettings maxOutboundConnectionsPerEndpoint="100"/>
></tcpTransport>
> </binding>
></customBinding>
> </bindings>
><services>
><service name="DistributedServices.PanelManagement.Services.GridService" >behaviorConfiguration="svcBehav">
> <endpoint >address="net.tcp://localhost:865/tcpsvces/services/GridService.svc"
> behaviorConfiguration="unitOfWorkBehavior" binding="customBinding" >bindingConfiguration="netTcpCustomBindingConfig"
> contract="DistributedServices.PanelManagement.Contracts.IGridService" >/>
> <endpoint address="mex" binding="customBinding" >bindingConfiguration="netTcpCustomBindingConfig" >contract="IMetadataExchange" />
> </service>
></services>
There are 2 general reasons for this error message. The first is with readerQuotas. Usually it is fixed just by increasing MaxStringContentLength (which you seem to have set large enough). I would increase other values in the readerQuotas to see if the problem goes away.
The second reason for this is if the data is serialized to go across the wire and when the deserialization is attempted the object has no setter defined for the data. So go through your data definition for your service and make sure you are not missing any setter definitions. Also if there are fields without setters that should NOT be passed across, make sure they are tagged as not serializable.
I haven't encountered a similar problem, which may have something to do with some configurations.
I suggest you try other bindings to create the service so that we could locate the problem, such as nettcpbinding, and configure the readerQuotas section.
Such as,
<bindings>
<netTcpBinding>
<binding name="mybinding" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" >
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<reliableSession ordered="false" inactivityTimeout="00:30:00"
enabled="true" />
</binding>
</netTcpBinding>
</bindings>
Besides, please check the below document. wish it is useful to you.
https://www.dofactory.com/topic/1339/session-has-faulted-timeout.aspx
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f7f4e91d-07e9-4139-a6ea-b203a71a4631/the-underlying-secure-session-has-faulted-before-the-reliable-session-fully-completed-the-reliable
http://girl-programmer.blogspot.com/2013/05/wcf-quotas.html
https://blog.petegoo.com/2008/04/15/wcf-exceptions-and-fault-contracts/
Feel free to let me know if the problem still exists.
Thanks in Adavance.
I am getting timeout exception after 5 minutes eventhough all timeouts are set to 10 minutes. Wcf is hosted in IIS.
Client config is as below
'
<netTcpBinding>
<binding name="TcpAuthBinding" closeTimeout="00:00:05" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" algorithmSuite="Default" />
</security>
</binding>
</netTcpBinding>
'
Server Config is as below
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
<serviceActivations>
<add service="ReportingService" relativeAddress ="ReportingService.svc" factory="Castle.Facilities.WcfIntegration.DefaultServiceHostFactory, Castle.Facilities.WcfIntegration"/>
</serviceActivations>
</serviceHostingEnvironment>
<behaviors>
<serviceBehaviors>
<behavior name="customBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="2147483647" />
<serviceTimeouts transactionTimeout="00:10:00" />
<exceptionMarshalling/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="customEndpointBehavior">
<protobuf maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<services>
<service name="Sample.ReportingService" behaviorConfiguration="customBehavior">
<endpoint binding="customBinding" bindingConfiguration="CustomNetTcpBinding" behaviorConfiguration="customEndpointBehavior" contract="Sample.IReportingService" />
</service>
</services>
<bindings>
<customBinding>
<binding name="CustomNetTcpBinding" closeTimeout="00:00:05" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
<transactionFlow/>
<gZipMessageEncoding enableCompression="true" innerMessageEncoding="textMessageEncoding">
<readerQuotas maxDepth="999999999" maxStringContentLength="999999999" maxArrayLength="999999999" maxBytesPerRead="999999999" maxNameTableCharCount="999999999" />
</gZipMessageEncoding>
<windowsStreamSecurity/>
<tcpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
</system.serviceModel>'
This is intermittent issue. In service I am fetching data from database server. Exception is as below
'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:09:59.9970000'. ---> 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:09:59.9970000'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
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.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.StartReading(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 ---
at Castle.Facilities.WcfIntegration.Proxy.WcfRemotingInterceptor.<>c__DisplayClass1.<PerformInvocation>b__0(WcfInvocation wcfInvocation)
at Castle.Facilities.WcfIntegration.WcfInvocation.Proceed()
at Castle.Facilities.WcfIntegration.RepairChannelPolicy.Apply(WcfInvocation wcfInvocation)
at Castle.Facilities.WcfIntegration.Proxy.WcfRemotingInterceptor.PerformInvocation(IInvocation invocation, IWcfChannelHolder channelHolder, Action`1 action)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IWcfChannelHolderProxy_3.ReportRequest(ReportDefinitionContract rpt)
at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)
at System.Threading.Tasks.Task.Execute()'
I wanted to create an extension less (file-less if possible) router endpoint via WCF Router Service that has customer user/password security policy. I am getting the following Fault Exception when attempting to route SOAP messages through it:
<s:Fault>
<faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
<faultstring xml:lang="en-US">An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</faultstring>
<detail>
<ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<HelpLink i:nil="true"/>
<InnerException i:nil="true"/>
<Message>An unexpected failure occurred. Applications should not attempt to handle this error. For diagnostic purposes, this English message is associated with the failure: 'Shouldn't allocate SessionChannels if session-less and impersonating'.</Message>
<StackTrace>at System.Runtime.Fx.AssertAndThrow(String description)
at System.ServiceModel.Routing.RoutingChannelExtension.get_SessionChannels()
at System.ServiceModel.Routing.RoutingService.GetOrCreateClient[TContract](RoutingEndpointTrait endpointTrait, Boolean impersonating)
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1.StartProcessing()
at System.ServiceModel.Routing.ProcessRequestAsyncResult`1..ctor(RoutingService service, Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.BeginProcessRequest[TContract](Message message, AsyncCallback callback, Object state)
at System.ServiceModel.Routing.RoutingService.System.ServiceModel.Routing.IRequestReplyRouter.BeginProcessRequest(Message message, AsyncCallback callback, Object state)
at AsyncInvokeBeginBeginProcessRequest(Object , Object[] , AsyncCallback , Object )
at System.ServiceModel.Dispatcher.AsyncMethodInvoker.InvokeBegin(Object instance, Object[] inputs, AsyncCallback callback, Object state)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace>
<Type>System.Runtime.Fx+InternalException</Type>
</ExceptionDetail>
</detail>
</s:Fault>
I did have to enabled AspNetCompability for the service host due to URL Routing.
Here are the steps that I followed:
I have set up a basic .net 4.0 web application with appropriate URL routing rules in RouteTable:
routes.Add(new ServiceRoute("routerservice", new CustomServiceHostFactory(), typeof(System.ServiceModel.Routing.RoutingService)));`
My CustomServiceHostFactory code:
public class CustomServiceHostFactory : ServiceHostFactory
{
protected override System.ServiceModel.ServiceHost CreateServiceHost(System.Type serviceType, System.Uri[] baseAddresses)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
var aspnet = host.Description.Behaviors.Find<AspNetCompatibilityRequirementsAttribute>();
if (aspnet == null)
{
aspnet = new AspNetCompatibilityRequirementsAttribute();
host.Description.Behaviors.Add(aspnet);
}
aspnet.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
return host;
}
}
In web.config file I define the service endpoint and behavior:
<services>
<service name="System.ServiceModel.Routing.RoutingService" behaviorConfiguration="GatewayServiceBehavior">
<endpoint address="" binding="basicHttpBinding" contract="System.ServiceModel.Routing.IRequestReplyRouter" bindingConfiguration="GatewaySecureBinding" />
</service>
</services>
The binding and behavior configurations are straight forward with just a simple username/password validation requirement:
<binding name="GatewaySecureBinding" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxBufferSize="65536" maxReceivedMessageSize="65536"
textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"
messageEncoding="Mtom">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<behavior name="GatewayServiceBehavior">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomLib.CustomUsernameValidator, CustomLib"/>
</serviceCredentials>
<routing filterTableName="RoutingTable1" routeOnHeadersOnly="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
I am calling a WCF service from a SharePoint site and getting an error on the client with below details, when relatively large object graph is returned.
On debugging the service I can see that is contructs the object correctly and the method returns the final object (that has the list of other objects) correctly. But I get exception on client side on the service method call.
Thie service/method works fine in most of the cases. Below are the service configurations (apologies for bad formatting)
Service Config:
<system.serviceModel>
<services>
<service behaviorConfiguration="StandardServiceBehaviour" name="Thd.K2.Web.DataServicesLibrary.Common.Services.AdminService">
<endpoint address="soap" binding="basicHttpBinding" name="AdminService" contract="Thd.K2.Web.DataServicesLibrary.Common.Interfaces.IAdminService" />
<endpoint address="mex" binding="mexHttpBinding" name="Metadata" contract="IMetadataExchange" kind="mexEndpoint" endpointConfiguration="" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="StandardServiceBehaviour">
<serviceMetadata httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="customBinding" hostNameComparisonMode="StrongWildcard" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00" maxReceivedMessageSize="1000000" maxBufferSize="1000000" maxBufferPoolSize="1000000" transferMode="Buffered" messageEncoding="Text" textEncoding="utf-8" bypassProxyOnLocal="false" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="214748364" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="webBinding" bypassProxyOnLocal="true" useDefaultWebProxy="false" hostNameComparisonMode="WeakWildcard" sendTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:05:00" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" />
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
</system.serviceModel>
Client method to create service instance
public static TServiceType GetServiceClient<TServiceType>(ConnStringsType connectionStringType, Page callingPage)
where TServiceType : class
{
var spUrl = GetConnectionString(connectionStringType, callingPage);
var result = new BasicHttpBinding(BasicHttpSecurityMode.None);
if(spUrl.ToLower().StartsWith("https"))
{
result = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
}
result.MaxReceivedMessageSize = int.MaxValue - 1;
result.MaxBufferSize = int.MaxValue-1;
if (!string.IsNullOrEmpty(spUrl))
{
return (TServiceType)Activator.CreateInstance(typeof(TServiceType), result, new EndpointAddress(spUrl));
}
return null;
}
Error:
An error occurred while receiving the HTTP response to http://localhost:90/AdminService.svc/soap. 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.
Stack:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.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 IAdminService.GetBlackoutPeriodsByDescription(String lang, String description)
at AdminServiceClient.GetBlackoutPeriodsByDescription(String lang, String description)
at EditBlackoutDates.LoadBlackout(String description)
I think this is about MaxItemsInObjectGraph property. Here is the answer to the similar problem.
#paramosh - Thanks a lot!!!
That did the trick. For others reference I was actually using a Non-RESTful WCF service. Hence I modified the solution as below
Calling below function before the web svc method call:
private void ExpandObjectGraphItems(AdminServiceClient svc)
{
var operations = svc.Endpoint.Contract.Operations;
foreach (var operation in operations)
{
var dataContractBehavior = operation.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
}
Added following attribute to service config:
<behavior name="StandardServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
I have a WCF service that uses message security over HTTPS using wsHttpBinding behind load balancer. When connects to the service on web browser via https, it works. However, Windowns forms client failed, using certificate over https,
Update
The request url is https, but after the exception saying http, below is exception tracing on server side:
For example: the request url is
https://www.server.com/wcf.svc'.
But it becomes
http://www.server.com:81/wcf.svc' on the server side. Is it the load balancer causing it.
System.ServiceModel.EndpointNotFoundException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
There was no channel actively listening at 'http://www.server.com:81/wcf.svc'. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
Below is the WCF service config:
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="false" />
</diagnostics>
<services>
<service behaviorConfiguration="verServiceBehaviour" name="ver.Service">
<endpoint address="ver" binding="wsHttpBinding" bindingConfiguration="wshttpbindingcfg"
contract="ver.Iver" behaviorConfiguration ="verEndpointBehaviour">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="mexhttpbinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://www.server.com/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<mexHttpBinding>
<binding name="mexhttpbinding" />
</mexHttpBinding>
<wsHttpBinding>
<binding name="wshttpbindingcfg" maxReceivedMessageSize="2000000000" sendTimeout="00:10:00">
<readerQuotas maxStringContentLength="2000000000"/>
<reliableSession ordered="true" enabled="false" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="verEndpointBehaviour">
<instanceContextBehavior/>
<verInspectorBehavior/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="verServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="100000000"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" trustedStoreLocation="LocalMachine" mapClientCertificateToWindowsAccount="false"/>
</clientCertificate>
<serviceCertificate
x509FindType="FindByThumbprint"
findValue="xxxx"
storeLocation="LocalMachine"
storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Below is client config:
<configuration>
<appSettings>
<add key="CertificateSubjectName" value="subjectName"/>
</appSettings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ver.IverHTTPS" 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="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://www.server.com/wcf.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ver.IverHTTPS"
contract="ServiceReference.verIver" name="verEndPoint" />
</client>
</system.serviceModel>
</configuration>
below is code in client using certificate:
var proxyClient = new ServiceReference.VerIVerClient("verEndPoint");
proxyClient.ClientCredentials.ClientCertificate.SetCertificate(
System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
System.Security.Cryptography.X509Certificates.StoreName.My,
System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
subjectName");
proxyClient.CallService()
Below is exception received at client side:
System.ServiceModel.EndpointNotFoundException was unhandled
Message=There was no endpoint listening at https://ver20.server.com/wcf.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.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 verClient.ServiceReference.verIver.GetClaimver(GetClaimverClaimApplication ClaimApplication)
at verClient.ServiceReference.verIverClient.GetClaimver(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\Service References\ServiceReference\Reference.cs:line 11330
at verClient.verForm.PostXmlTover(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\verForm.cs:line 1408
at verClient.verForm.PostButton_Click(Object sender, EventArgs e) in D:\Projects\ver\verClient\verForm.cs:line 34
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at verClient.Program.Main() in D:\Projects\ver\verClient\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.WebException
Message=The remote server returned an error: (404) Not Found.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException:
Review the configuration of your load balancer, and make sure that the requests are being for warded to the correct host AND PORT number. If the port number you chose is not standard, make sure to adjust the IIS Site Binding and the base address of your service.
One important thing to understand about transport security is that it has to be configured on a "hop" by "hop" basis. In your example, you have two hops (client) -> (load balancer) and (load balancer) -> (server).
Securing your connection from the client to the load balancer doesn't automatically configure security from the load balancer to the server. You need to install and configure an ssl certificate on both the load balancer and the server.
Your initial https request ended up being an http request on the server, that is a good indication that you did not configure a secure channel between the load balancer and the server.
If you do not wish to secure the connection between the load balancer and the server, then expose your service without transport security. With this, you can still have the communication from the client to the load balancer (the first hop) on ssl.