Answered by:
IDispatchMessageInspector.AfterReceiveRequest - skip operation and manually generate custom response instead

Question
-
Hi,
I am using a service behavior class that implements IDispatchMessageInspector.AfterReceiveRequest to handle special cases that require skipping the actual operation's code and instead manually crafting a response message.
Although it not documented in http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.idispatchmessageinspector.afterreceiverequest.aspx
It has been pointed out in various forum threads that setting ref request parameter to null will skip the normal message processing and transition directly to BeforeSendReply. I have tracing enabled on my service and observe that underneath it still tries to deserialize the message and throws an exception:
NullReferenceException: Object reference not set to an instance of an object.
System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
So my question is - Am I doing it the right way and this exception is expected behavior or there is a better alternative.
BTW, this exception causes my custom IErrorHandler class be invoked as well.
Thanks for help.
Tuesday, June 14, 2011 4:03 PM
Answers
-
This is not correct (setting request to null to bypass the service), unfortunately WCF doesn't have any out-of-the-box way of doing that.
You can, however, use a few more of the extensibility points in WCF to make this scenario work. You'll need at least an IDispatchMessageFormatter (to prevent the message from being read / deserialized since it's not necessary) and an IOperationInvoker (to actually bypass invoking the service method). You can use the operation context to pass information between those extensibility points.
You can find more information about those three interfaces in my ongoing blog series about WCF extensibility points:
- IDispatchMessageInspector: http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx
- IDispatchMessageFormatter: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx
- IOperationInvoker: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/17/wcf-extensibility-ioperationinvoker.aspx
The code which uses those extensions to skip the operation based on a decision made in the message inspector:
public class Post_55ef7692_25dc_4ece_9dde_9981c417c94a { [ServiceContract(Name = "ITest", Namespace = "http://tempuri.org/")] public interface ITest { [OperationContract] string Echo(string text); } public class Service : ITest { public string Echo(string text) { return text; } } static Binding GetBinding() { BasicHttpBinding result = new BasicHttpBinding(); return result; } public class MyOperationBypasser : IEndpointBehavior, IOperationBehavior { internal const string SkipServerMessageProperty = "SkipServer"; public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyInspector(endpoint)); } public void Validate(ServiceEndpoint endpoint) { } public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.Formatter = new MyFormatter(dispatchOperation.Formatter); dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker); } public void Validate(OperationDescription operationDescription) { } class MyInspector : IDispatchMessageInspector { ServiceEndpoint endpoint; public MyInspector(ServiceEndpoint endpoint) { this.endpoint = endpoint; } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { Message result = null; HttpRequestMessageProperty reqProp = null; if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { reqProp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } if (reqProp != null) { string bypassServer = reqProp.Headers["X-BypassServer"]; if (!string.IsNullOrEmpty(bypassServer)) { result = Message.CreateMessage(request.Version, this.FindReplyAction(request.Headers.Action), new OverrideBodyWriter(bypassServer)); } } return result; } public void BeforeSendReply(ref Message reply, object correlationState) { Message newResult = correlationState as Message; if (newResult != null) { reply = newResult; } } private string FindReplyAction(string requestAction) { foreach (var operation in this.endpoint.Contract.Operations) { if (operation.Messages[0].Action == requestAction) { return operation.Messages[1].Action; } } return null; } class OverrideBodyWriter : BodyWriter { string bypassServerHeader; public OverrideBodyWriter(string bypassServerHeader) : base(true) { this.bypassServerHeader = bypassServerHeader; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement("EchoResponse", "http://tempuri.org/"); writer.WriteStartElement("EchoResult"); writer.WriteString(this.bypassServerHeader); writer.WriteEndElement(); writer.WriteEndElement(); } } } class MyFormatter : IDispatchMessageFormatter { IDispatchMessageFormatter originalFormatter; public MyFormatter(IDispatchMessageFormatter originalFormatter) { this.originalFormatter = originalFormatter; } public void DeserializeRequest(Message message, object[] parameters) { if (message.Properties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { Message returnMessage = message.Properties[MyOperationBypasser.SkipServerMessageProperty] as Message; OperationContext.Current.IncomingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage); OperationContext.Current.OutgoingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage); } else { this.originalFormatter.DeserializeRequest(message, parameters); } } public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { return null; } else { return this.originalFormatter.SerializeReply(messageVersion, parameters, result); } } } class MyInvoker : IOperationInvoker { IOperationInvoker originalInvoker; public MyInvoker(IOperationInvoker originalInvoker) { if (!originalInvoker.IsSynchronous) { throw new NotSupportedException("This implementation only supports synchronous invokers"); } this.originalInvoker = originalInvoker; } public object[] AllocateInputs() { return this.originalInvoker.AllocateInputs(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { outputs = null; return null; // message is stored in the context } else { return this.originalInvoker.Invoke(instance, inputs, out outputs); } } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { throw new NotSupportedException(); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { throw new NotSupportedException(); } public bool IsSynchronous { get { return true; } } } } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), GetBinding(), ""); endpoint.Behaviors.Add(new MyOperationBypasser()); foreach (var operation in endpoint.Contract.Operations) { operation.Behaviors.Add(new MyOperationBypasser()); } host.Open(); Console.WriteLine("Host opened"); ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); Console.WriteLine(proxy.Echo("Hello")); Console.WriteLine("And now with the bypass header"); using (new OperationContextScope((IContextChannel)proxy)) { HttpRequestMessageProperty httpRequestProp = new HttpRequestMessageProperty(); httpRequestProp.Headers.Add("X-BypassServer", "This message will not reach the service operation"); OperationContext.Current.OutgoingMessageProperties.Add( HttpRequestMessageProperty.Name, httpRequestProp); Console.WriteLine(proxy.Echo("Hello")); } ((IClientChannel)proxy).Close(); factory.Close(); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } }
Carlos Figueira- Marked as answer by Yi-Lun Luo Tuesday, June 21, 2011 9:45 AM
Tuesday, June 14, 2011 11:42 PM -
To stop the message ever being processed to need to plug in below the service model layer
You would have to write a Protocol Channel [0]. The channel layer works on teh decorator pattern which each channel handing off to the next in the chain. You would need to not workward down the chain but simply create the message you need to send back and send back immediately.
However, extending the channel layer is not for the faint of heart - it is much more complex and less well documented than the service model layer extension points. There's an article about creating a protocol channel here [1]
[0] http://msdn.microsoft.com/en-us/library/ms729840.aspx
[1] http://msdn.microsoft.com/en-us/library/aa717050.aspx
Richard Blewett, thinktecture - http://www.dotnetconsult.co.uk/weblog2
Twitter: richardblewett- Marked as answer by Yi-Lun Luo Tuesday, June 21, 2011 9:45 AM
Wednesday, June 15, 2011 7:20 AM
All replies
-
This is not correct (setting request to null to bypass the service), unfortunately WCF doesn't have any out-of-the-box way of doing that.
You can, however, use a few more of the extensibility points in WCF to make this scenario work. You'll need at least an IDispatchMessageFormatter (to prevent the message from being read / deserialized since it's not necessary) and an IOperationInvoker (to actually bypass invoking the service method). You can use the operation context to pass information between those extensibility points.
You can find more information about those three interfaces in my ongoing blog series about WCF extensibility points:
- IDispatchMessageInspector: http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx
- IDispatchMessageFormatter: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx
- IOperationInvoker: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/17/wcf-extensibility-ioperationinvoker.aspx
The code which uses those extensions to skip the operation based on a decision made in the message inspector:
public class Post_55ef7692_25dc_4ece_9dde_9981c417c94a { [ServiceContract(Name = "ITest", Namespace = "http://tempuri.org/")] public interface ITest { [OperationContract] string Echo(string text); } public class Service : ITest { public string Echo(string text) { return text; } } static Binding GetBinding() { BasicHttpBinding result = new BasicHttpBinding(); return result; } public class MyOperationBypasser : IEndpointBehavior, IOperationBehavior { internal const string SkipServerMessageProperty = "SkipServer"; public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyInspector(endpoint)); } public void Validate(ServiceEndpoint endpoint) { } public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) { } public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) { dispatchOperation.Formatter = new MyFormatter(dispatchOperation.Formatter); dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker); } public void Validate(OperationDescription operationDescription) { } class MyInspector : IDispatchMessageInspector { ServiceEndpoint endpoint; public MyInspector(ServiceEndpoint endpoint) { this.endpoint = endpoint; } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { Message result = null; HttpRequestMessageProperty reqProp = null; if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { reqProp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } if (reqProp != null) { string bypassServer = reqProp.Headers["X-BypassServer"]; if (!string.IsNullOrEmpty(bypassServer)) { result = Message.CreateMessage(request.Version, this.FindReplyAction(request.Headers.Action), new OverrideBodyWriter(bypassServer)); } } return result; } public void BeforeSendReply(ref Message reply, object correlationState) { Message newResult = correlationState as Message; if (newResult != null) { reply = newResult; } } private string FindReplyAction(string requestAction) { foreach (var operation in this.endpoint.Contract.Operations) { if (operation.Messages[0].Action == requestAction) { return operation.Messages[1].Action; } } return null; } class OverrideBodyWriter : BodyWriter { string bypassServerHeader; public OverrideBodyWriter(string bypassServerHeader) : base(true) { this.bypassServerHeader = bypassServerHeader; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement("EchoResponse", "http://tempuri.org/"); writer.WriteStartElement("EchoResult"); writer.WriteString(this.bypassServerHeader); writer.WriteEndElement(); writer.WriteEndElement(); } } } class MyFormatter : IDispatchMessageFormatter { IDispatchMessageFormatter originalFormatter; public MyFormatter(IDispatchMessageFormatter originalFormatter) { this.originalFormatter = originalFormatter; } public void DeserializeRequest(Message message, object[] parameters) { if (message.Properties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { Message returnMessage = message.Properties[MyOperationBypasser.SkipServerMessageProperty] as Message; OperationContext.Current.IncomingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage); OperationContext.Current.OutgoingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage); } else { this.originalFormatter.DeserializeRequest(message, parameters); } } public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { return null; } else { return this.originalFormatter.SerializeReply(messageVersion, parameters, result); } } } class MyInvoker : IOperationInvoker { IOperationInvoker originalInvoker; public MyInvoker(IOperationInvoker originalInvoker) { if (!originalInvoker.IsSynchronous) { throw new NotSupportedException("This implementation only supports synchronous invokers"); } this.originalInvoker = originalInvoker; } public object[] AllocateInputs() { return this.originalInvoker.AllocateInputs(); } public object Invoke(object instance, object[] inputs, out object[] outputs) { if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty)) { outputs = null; return null; // message is stored in the context } else { return this.originalInvoker.Invoke(instance, inputs, out outputs); } } public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state) { throw new NotSupportedException(); } public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result) { throw new NotSupportedException(); } public bool IsSynchronous { get { return true; } } } } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), GetBinding(), ""); endpoint.Behaviors.Add(new MyOperationBypasser()); foreach (var operation in endpoint.Contract.Operations) { operation.Behaviors.Add(new MyOperationBypasser()); } host.Open(); Console.WriteLine("Host opened"); ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); Console.WriteLine(proxy.Echo("Hello")); Console.WriteLine("And now with the bypass header"); using (new OperationContextScope((IContextChannel)proxy)) { HttpRequestMessageProperty httpRequestProp = new HttpRequestMessageProperty(); httpRequestProp.Headers.Add("X-BypassServer", "This message will not reach the service operation"); OperationContext.Current.OutgoingMessageProperties.Add( HttpRequestMessageProperty.Name, httpRequestProp); Console.WriteLine(proxy.Echo("Hello")); } ((IClientChannel)proxy).Close(); factory.Close(); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } }
Carlos Figueira- Marked as answer by Yi-Lun Luo Tuesday, June 21, 2011 9:45 AM
Tuesday, June 14, 2011 11:42 PM -
To stop the message ever being processed to need to plug in below the service model layer
You would have to write a Protocol Channel [0]. The channel layer works on teh decorator pattern which each channel handing off to the next in the chain. You would need to not workward down the chain but simply create the message you need to send back and send back immediately.
However, extending the channel layer is not for the faint of heart - it is much more complex and less well documented than the service model layer extension points. There's an article about creating a protocol channel here [1]
[0] http://msdn.microsoft.com/en-us/library/ms729840.aspx
[1] http://msdn.microsoft.com/en-us/library/aa717050.aspx
Richard Blewett, thinktecture - http://www.dotnetconsult.co.uk/weblog2
Twitter: richardblewett- Marked as answer by Yi-Lun Luo Tuesday, June 21, 2011 9:45 AM
Wednesday, June 15, 2011 7:20 AM -
This doesn't actually work. The line:
public void DeserializeRequest(Message message, object[] parameters) { if (message.Properties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
will never be true in the if statement. Nothing in the endpoint inspector adds this property to the message so the formatter is never going to switch to the bypass. Am i missing something here?Thursday, December 22, 2011 5:21 PM