WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

I've just spent a couple of hours trying to track down a customer issue with one of our WCF services. Below was part of the unit test I was suing to test the service.

using (var client = new MemberServiceClient())
{
    client.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["username"];
    client.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["password"];
    client.CreateMember(mem);
    client.DeleteMember(mem.ExternalRef);
}

and the exception it was throwing was:

failed: System.ServiceModel.CommunicationObjectFaultedException : The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.
	
	Server stack trace: 
	at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)
	
	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 System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
	at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)
	at System.ServiceModel.ClientBase`1.Close()
	at System.ServiceModel.ClientBase`1.System.IDisposable.Dispose()

When I debugged the code the code actually fails at the CreateMember line not at the close method indicated at by the stack trace. Then I realised that this was one of thoes WCF silly moments - don't use using blocks!. Yes believe it or not if you use a using block around a WCF client and it fails when the using block calls the dispose method it throws a new excpetion masking the real exception.

 

The code below is some helper methods we use for making WCF clients are cleaned up correctly.

 

/// <summary>
/// WCF proxys do not clean up properly if they throw an exception. This method ensures that the service proxy is handeled correctly.
/// Do not call TService.Close() or TService.Abort() within the action lambda.
/// </summary>
/// <typeparam name="TService">The type of the service to use</typeparam>
/// <param name="action">Lambda of the action to performwith the service</param>

public static void Using<TService>(Action<TService> action)
	where TService : ICommunicationObject, IDisposable, new()
{
	var service = new TService();
	bool success = false;
	try
	{
		action(service);
		if (service.State != CommunicationState.Faulted)
		{
			service.Close();
			success = true;
		}
	}
	finally
	{
		if (!success)
		{
			service.Abort();
		}
	}
}

 

Changing the code to using our service helper methods.

 

ServiceHelper.Using(
    client =>

        {
            client.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["username"];
            client.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["password"];
            client.CreateMember(mem);
            client.DeleteMember(mem.ExternalRef);
        }
    );

 

Now the code exposed the actual exception that was causing the issue.

 

failed: System.ServiceModel.Security.MessageSecurityException : An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
  ----> System.ServiceModel.FaultException : An error occurred when verifying security for the message.
	
	Server stack trace: 
	at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
	at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
	at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
	at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
	at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
	at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.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.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
	at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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)


This exception had me stumped as I had never come across it before but after a bit of digging I discovered that the server time was 7 minutes late and that changing the time fixed the issue. Still trying to figure out how the server's time got out of synced.

Published 26 May 2009 13:06 by Damien McGivern
Filed under: ,

Comments

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

16 July 2009 05:47 by Ken Smith

Very helpful pointer about the using() bit.  I was running into the same error (on the server), and I couldn't figure out where that error message was coming from.  I knew about the problems with the using() pattern on WCF, but I was using somebody else's code, and didn't notice it -- and didn't realize that it was hiding the real error.  I got rid of the using wrapper, and now I just have to figure out the real error :-).

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

07 August 2009 17:14 by Steve

I love the helper method with the lambda approach you took.  However, this won't work when calling WCF methods asynchronously.  You end up getting an error, "Async End called on wrong channel."

The reason, of course, is because you're creating a new client and closing it within the Using<>() method.

Any suggestions for modifying this to get it to work with Async method calls?

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

19 August 2009 22:03 by sunny

Hi mate i have similar issue. but i don't get exception. in the client trace i found this error:

Description Failed to open System.ServiceModel.Security.SecuritySessionClientSettings`1+ClientSecurityDuplexSessionChannel[System.ServiceModel.Channels.IDuplexSessionChannel]

i have tried to find a fix but been unsuccessful. Can you help me with it?

sunny

s26f84 at gmail

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

21 October 2009 09:15 by nk17

I also have below error.

"Async End called on wrong channel." at the time of  nor.EndProductList(ar);

Begin handler is as below

nor.BeginProductList(acb, extraData);

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

02 November 2009 06:33 by Sunil Bindra

Hi Dear

I have same issue. I am trying this on same machine. As my client and server is on same machine so issue of time. I am using even maxClockSkew=infinite. Even then i am getting this exception. Can any help me out?

Below is my Code at client Machine

HealthCheck.McmSecurityService.SecurityServiceClient SctyClient = new HealthCheck.McmSecurityService.SecurityServiceClient();

               //SctyClient.ClientCredentials.UserName.UserName = "MCM" + "~" + "MCM" + "~" + "MCM";

               //SctyClient.ClientCredentials.UserName.Password = "MCM";

               //if(SctyClient.State!=CommunicationState.Faulted)

               SctyClient.ClientCredentials.UserName.UserName = "sf" + "~" + "suneelk" + "~" + "infogain";

               SctyClient.ClientCredentials.UserName.Password = "infogain";

               SctyClient.Open();

               //SctyClient.

               //HealthCheck.McmSecurityService.UserInfo objUserInfo = SctyClient.ValidateUser("suneelk", "sf", "infogain");

               //SctyClient.ValidateUser("suneelk", "sf", "infogain");

               //DateTime date = DateTime.Today;

               string Sec_Str = SctyClient.HealthCheck();

               SctyClient.Close();

The exception I am getting is :

{"An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail."}

Inner Exceoption is :

{"An error occurred when verifying security for the message."}

Stack Trace is :

"\r\nServer stack trace: \r\n   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)\r\n   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)\r\n   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)\r\n   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)\r\n   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)\r\n\r\nException rethrown at [0]: \r\n"

thanks in advance

# Ensuring WCF Correctly Reports Errors&nbsp;|&nbsp;Exigency In Specie

Pingback from  Ensuring WCF Correctly Reports Errors&nbsp;|&nbsp;Exigency In Specie

# links for 2010-01-08 &laquo; dstelow notes&#8230;

08 January 2010 23:08 by links for 2010-01-08 « dstelow notes…

Pingback from  links for 2010-01-08 &laquo;  dstelow notes&#8230;

# WCF.Note.Exception Plus - nonocast

28 March 2010 17:50 by WCF.Note.Exception Plus - nonocast

Pingback from  WCF.Note.Exception Plus - nonocast

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

13 May 2010 22:44 by Scott

For those of you who are getting "Async End called on wrong channel." You should not be using a using block on Async calls anyway. don't wrap it and put your Close() inside your AsyncEnd() callback function.

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

28 May 2010 13:55 by mmckechney

Your solution worked great. Thank you for the well thought out and elegent solution!

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

02 June 2010 07:50 by Toyin

My solution or temporary fix, is to test for the faulted state, if it is then close. You'll need to catch the error. Once you by pass that line of code, you can then open the communication. Like so.

if (Proxy.State == System.ServiceModel.CommunicationState.Faulted)

           {

               try

               {

                   Proxy.Close();

               }

               catch { }

               while (i < 4 && !success)

               {

                   success = OpenProxy();

                   i += 1;

               }

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

30 August 2010 16:07 by papabear

Saved me alot of trouble, thanks!

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

13 October 2010 12:32 by raph1707

Do not use what Toyin wrote.

If the communicationState is Faulted, just call

Proxy.Abort();

# Silverlight and ASP.NET compatible WCF over SSL

21 January 2011 09:36 by Nathan J Pledger

WCF, as you probably know, can be a hugely flexible, but equally complicated beast. The domain knowledge

# Silverlight and ASP.NET compatible WCF over SSL using custom username/password authentication

21 January 2011 09:54 by Blogging About .NET

WCF, as you probably know, can be a hugely flexible, but equally complicated beast. The domain knowledge

# re: WCF CommunicationObjectFaultedException " cannot be used for communication because it is in the Faulted state" MessageSecurityException "An error occurred when verifying security for the message"

16 June 2011 07:55 by enrique.prados@avalne.es

If I want use ServiceHelper.Using with endpointname or UriAddress ?? thx