3

I'm trying to implement a simple message inspector that writes the message to the debug window from an example on MSDN:

public class MyMessageInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        System.Diagnostics.Debug.WriteLine(request.ToString());
        return null;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        System.Diagnostics.Debug.WriteLine(reply.ToString());
    }
}

The reply is writing as expected. However the request seems to be null. Any ideas on what could be going wrong? I'm using a Service Reference proxy with a console app as the client.

I'm using basicHttpbinding and hosting with IIS with svc file. The parameter for my web method is a complex type. I'm not sure if that makes a difference.

Greg Sansom
  • 19,197
  • 6
  • 54
  • 72
Quadwwchs
  • 1,435
  • 3
  • 15
  • 19

2 Answers2

1

Try CreateBufferedCopy (i.e clone) of the message request first: http://msdn.microsoft.com/en-us/library/ms734675.aspx (Copying a Message into a Buffer).

More info here under "Now for the message inspection part": http://binarymist.net/2010/06/14/message-inspection-in-wcf/

Rebecca
  • 12,888
  • 10
  • 84
  • 127
  • Thanks for the info. I tried creating a buffer but still not working. I'll try the example in your link as well. – Quadwwchs Jan 04 '11 at 14:49
  • Request buffer is not needed for `request.ToString()`. – Greg Sansom Jan 24 '11 at 04:47
  • 1
    The MSDN link states with regards to "Extracting Message Body Data": You can access the body of a Message only once, regardless of how it is accessed. A message object has a State property, which is initially set to Created. The three access methods described in the preceding list set the state to Written, Read, and Copied, respectively. Additionally, a Close method can set the state to Closed when the message body contents are no longer required. The message body can be accessed only in the Created state, and there is no way to go back to the Created state after the state has changed. – Rebecca Jan 24 '11 at 09:16
  • But if `request == null`, how could we use `CreateBufferedCopy` to fix the problem? – Greg Sansom Jan 27 '11 at 05:39
0

I have copy and pasted the MyMessageInspector class and added the behavior to my my web service, and it works fine - when the web service is called, the SOAP envelope is printed as XML.

Do you have any other MessageInspectors in your project? If so, it is possible that one of them is setting request = null - this will cause the problem you're having, since the request parameter is ref.

If not, what makes you say request is null? Are you getting a NullReferenceException on the Debug.WriteLine(..) statement?

Greg Sansom
  • 19,197
  • 6
  • 54
  • 72