views:

425

answers:

2

I'm looking for a way to log both requests and responses in a WCF REST service. The WCF REST starter kit comes with a RequestInterceptor class which can be used to intercept requests, but there does not seem to be an equivalent for responses. Ideally, I'd like to be able to intercept a response just before it's sent over the wire, e.g. when the underlying service method returns. Any suggestions?

A: 

There is a technic in WCF: you create InstrumentedOperationAttribute that derives from Attribute, IOperationBehavior.

Inside you implement:

public void ApplyDispatchBehavior(

   OperationDescription operationDescription,

   DispatchOperation dispatchOperation

   )
{

  dispatchOperation.ParameterInspectors.Add(

     new ServerPI()

     );

}

and the ServerPI() class is what does the magic: you do everything you need in beforecall and aftercall methods:

  class ServerPI : IParameterInspector
  {

    public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
      Guid result = (Guid)correlationState;
      // ...
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
      string parameter1 = inputs[0] as string;
      return Guid.NewGuid();
    }

  }
Dani
+1  A: 

Notice that if you want to intercept the raw message, and not the parameters, you can inject your implementation of IDispatchMessageInspector instead of the IParameterInspector extension point that Dani suggests.

tomasr