Search code examples
c#.netentity-frameworkwcf-data-services

How to capture the response of a call to a WCF Data Service?


Question: How do I capture the response (or, more specifically, the status code of the response) of a call to a WCF Data Service?

Elaboration: I have a rather simple WCF Data Service with a logger. Something along the lines of:

public class MyDefault : DataService<MyEntities>
{
    private Logger logger = LogManager.GetCurrentClassLogger();

    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }

    protected override void OnStartProcessingRequest(ProcessRequestArgs args)
    {
        logger.Info(args.RequestUri);
    }

    protected override void HandleException(HandleExceptionArgs args)
    {
        logger.Error(args.ResponseStatusCode)
    }
}

The goal is to get a log of all requests made, as well as their result. The code above manages to almost do that, as 404's do get logged, just as custom errors and when things really go wrong.

But what misses is when things go right. Without that information, the logs look really weird and it's not possible to distinguish between something really weird happening (ie: no response and no logs) or when everything is working the way it should (ie: success, but still no log).

So the real question is: How can I use the same logger I use for incoming requests to log the status code of the response?

[EDIT]
I may have oversimplified. This is part of a bigger system that already has logging in place. The point is to keep all logging in one place and one format. I have briefly looked at Message Logging before. Maybe not enough, I'm looking more into that right now.

However, even if I'm able to mold it to my needs, the original question has piqued my interest and I would still like to explore whether it's possible to at least look at the HttpResponse object.


Solution

  • You can try to access the DataServiceProcessingPipeline object and attach to the ProcessedRequest event:

    ProcessingPipeline.ProcessedRequest += ProcessingPipeline_ProcessedRequest;
    
    void ProcessingPipeline_ProcessedRequest(object sender, DataServiceProcessingPipelineEventArgs e)
    {
        int statusCode = e.OperationContext.ResponseStatusCode;
    }