Dangers of Application Domain Recycling

Secure calls to a hosted service are intermittently failing with the following error message:

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

The inner exception looks like this:

The message could not be processed. This is most likely because the action '*' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.

Why are these calls failing?

A sometimes overlooked aspect of hosted services is that the host controls the service lifetime. If you host your service in IIS, then it is possible that the application domain your service resides in will eventually be recycled. For instance, you may touch a configuration file that causes IIS to stop and restart all of your web services. When this occurs, the next call to the web service creates a fresh instance that knows nothing about any past security contexts that you may be using. These kinds of situations can cause the above error message because the service is not expecting a secured message and doesn't know how to send back a secured fault.

Next time: Mixing Message Contract Attributes