Why is the RequestContext Null?

Today's post somehow ended up getting bumped to Sunday.  All is well now.  Sorry for the late start.

In the request/reply model, the RequestContext object is the link between the request that comes in and the reply that goes out. When the server receives a request, it provides a RequestContext instance that represents the request to the channel. The request context contains the original request message among other useful properties. This request context is then stashed inside the OperationContext for retrieval by your service. You typically hit OperationContext.Current.RequestContext to access the request of the current operation. You might notice that this RequestContext member is sometimes null. That can be intentional.

Since the role of the request context is to link requests and replies, it doesn't make since to have a request context when you don't have a reply. For a one-way operation on top of the request/reply model, the server receives requests but doesn't send back a response to the client. If you were not expecting the request context to be null, the first thing you should check is whether you marked the operation contract with IsOneWay.

The downside of the request context being null for one-way operations is that you don't have access to the original request inside the operation. This may not pose a problem for some operation implementations, but we have heard from people who were interested in using the request message. One way to obtain the request is to put in an IDispatchMessageInspector. This gives you the Message instance that would normally be accessed through the request context.

If you're using a feature that depends on the operation dispatch, such as transactions, then you don't have access to that feature's context inside the message inspector. This requires a slightly more complicated workaround to achieve the same results. The simplest message inspector is to just store a copy of the message for later use. You can then plug in at another time, such as with an IParameterInspector, when you have access to the additional context you need.

Next time: Cancelling Streams

Comments (1)

  1. One of the changes in a recent version was that MEX endpoints no longer get added to your service host…

Skip to main content