1

I have a RESTful WCF service that have a service method say BeginX()

Inside BeginX, I call my static Validate function in a static helper class. Inside the static Validate method, can I call WebOperationContext.Current.OutgoingResponse.StatusCode = blah?

What is the expected behavior when current context is called from inside static methods in my service?

(I tried prototyping it, but I can't seem to get a WebOperationContext when I try to get it from an in-proc WCF service that runs in my console app)

kosh
  • 551
  • 1
  • 9
  • 22

1 Answers1

2

WebOperationContext.Current is a static property, and is available to any method, static or otherwise, as long as the method is running on that thread.

private static void CheckWebOperationContext()
{
   Trace.WriteLine(string.Format("CheckWebOperationContext: {0}", WebOperationContext.Current == null ? "WebOperationContext is null" : "WebOperationContext is not null"));

}

[OperationContract]
[WebInvoke]
public void DemonstrateWebOperationContext()
{
    Trace.WriteLine(string.Format("GetPlayerStatus: {0}", WebOperationContext.Current == null ? "WebOperationContext is null" : "WebOperationContext is not null"));
    CheckWebOperationContext();
    // Now call the same function on a different thread
    Action act = () =>
        {
            CheckWebOperationContext();
        };
    var iAsyncResult = act.BeginInvoke(null, null);
    iAsyncResult.AsyncWaitHandle.WaitOne();
}

This will result in the following outputs:

GetPlayerStatus: WebOperationContext is not null

CheckWebOperationContext: WebOperationContext is not null

CheckWebOperationContext: WebOperationContext is null

The first call to CheckWebOperationContext is on the same thread, so the context is available to it. The second call is on a different thread, so the context is not available.

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205