Reading the SOAP message headers for any set of messages can be useful when diagnosing problems. This code allows you to do just that.
To run:
Original posting: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/fa3f4c55-5835-43f2-892f-737b4bccb598
using
System;
System.Collections.Generic;
System.ServiceModel;
System.ServiceModel.Description;
System.ServiceModel.Dispatcher;
public
class
MessageInspectorSample
{
static
void
Main()
// This runs the whole show!
Run();
}
[ServiceContract]
// A very simple service contract. Echo and Add.
interface
ITest
[OperationContract]
string
Echo(
text);
int
Add(
x,
y);
Service : ITest
text)
return
text;
y)
x + y;
MyInspector : IClientMessageInspector, IEndpointBehavior
// These lists store the messages for later retrieval.
List<
> sentMessages =
new
>();
> receivedMessages =
#region IClientMessageInspector Members
AfterReceiveReply(
ref
System.ServiceModel.Channels.Message reply,
object
correlationState)
// Save the reply to the list.
receivedMessages.Add(reply.ToString());
BeforeSendRequest(
System.ServiceModel.Channels.Message request, IClientChannel channel)
// Save the request to the list.
sentMessages.Add(request.ToString());
null
;
#endregion
#region IEndpointBehavior Members
AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{}
ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
// Add this implementation to the inspectors.
clientRuntime.MessageInspectors.Add(
this
);
ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{ }
Validate(ServiceEndpoint endpoint)
Run()
baseAddress =
"http://"
+ Environment.MachineName +
":8000/Service"
ServiceHost host =
ServiceHost(
typeof
(Service),
Uri(baseAddress));
ServiceEndpoint endpoint = host.AddServiceEndpoint(
(ITest),
BasicHttpBinding(),
""
host.Open();
Console.WriteLine(
"Host opened at "
+ baseAddress);
MyInspector inspector =
MyInspector();
ChannelFactory<ITest> factory =
ChannelFactory<ITest>(
EndpointAddress(baseAddress));
factory.Endpoint.Behaviors.Add(inspector);
ITest proxy = factory.CreateChannel();
proxy.Echo(
"Hello world"
proxy.Add(123, 456);
((IClientChannel)proxy).Close();
factory.Close();
host.Close();
"Sent messages:"
foreach
(
sent
in
inspector.sentMessages)
Console.WriteLine(sent);
Console.WriteLine();
"*******************************************"
"Received messages:"
received
inspector.receivedMessages)
Console.WriteLine(received);
Console.ReadLine();
+++++++++++++++++++++++++++++++++++++
To add complexity, use a different binding such as WSHttpBinding with different security requirements.
This article is also available in the following languages: