Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between RequestInterceptor and MessageInspector?

I have two queries here :-

1) What is the basic difference between Microsoft.ServiceModel.Web.RequestInterceptor and System.ServiceModel.Dispatcher.DispatchRuntime.MessageInspectors (IdispatchMessageInterceptor)

Both appears to be Request/Message interceptors which can be used to implement custom validation/interceptors in the request pipeline.

When to use one on another?

2) Also how to plugin RequestInterceptor in RouteTable.Routes.Add(new ServiceRoute())

I have class like this -

public class AuthenticationInterceptor : RequestInterceptor
{
   //Authentication logic goes here......
}

and a route definition like this : -

RouteTable.Routes.Add(new ServiceRoute(routePrefix, new MyServiceHostFactory(container, (sh) => {
                foreach (System.ServiceModel.Dispatcher.ChannelDispatcher cd in sh.ChannelDispatchers)
                {
                    foreach (System.ServiceModel.Dispatcher.EndpointDispatcher ed in cd.Endpoints)
                    {
                        ed.DispatchRuntime.MessageInspectors.Add(new AuthenticationInterceptor());
                    }
                }
                return sh; })));

Here is the definition of MyServiceHostFactory: -

public MyServiceHostFactory(IocContainer container, Func<ServiceHost, ServiceHost> createservicehost = null);

Now it is throwing following error : -

The best overloaded method match for 'System.Collections.Generic.SynchronizedCollection<System.ServiceModel.Dispatcher.IDispatchMessageInspector>.Add(System.ServiceModel.Dispatcher.IDispatchMessageInspector)' has some invalid arguments

at this line : -

ed.DispatchRuntime.MessageInspectors.Add(new AuthenticationInterceptor());

I know why, it is just because I am trying to hookup RequestInterceptor in MessageInspector. Both comes in different interface hierarchy.

So what should I do here?

Edit:

Also note, I cannot change AuthenticationInterceptor logic as the code in not under my control.

like image 990
Anil Purswani Avatar asked Jun 18 '14 07:06

Anil Purswani


1 Answers

Here are the answers to your questions(you need to read through point number 2 to understand Interceptors and Inspectors a little):

1. Solution to the Error (you need to add your code logic to it )

Implement IDispatchMessageInspector in the following code. Please note that the name of the following class should change to inspector, but as you have mentioned you cannot change it so you should implement the interface here. Otherwise, it is recommended to create another class with Matching Inspector suffix and implementation.

public class AuthenticationInterceptor : RequestInterceptor, IDispatchMessageInspector
{
    //Authentication logic goes here......
    object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        //Your code here.
    }
    void IDispatchMessageInspector.BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        //Your code here.
    }
}

2. Difference between RequestInterceptor and MessageInspectors

In any client server communication there can be two important phases of communication. First, when a client establishes connection with the server and second when they both communicate.

When establishing the connection it is not necessary that the client which is trying to establish the connection is a valid client. It could be an unauthorized request as well or it could be possible that the request is valid but not intended to the destined server and requires authorization or connection rerouting.

A good example of rerouting is when :

  1. you want regional client/servers to avoid cross region communications but one of the client(which is valid) but tries to connect to a different region server.

  2. You want the servers selectively decide if you wish to allow cross region client-server communications for a few exceptional users.

There could be even more complex rerouting scenarios which is out of scope of this answer.

So in WCF, the Rest starter kit provides you additional ability to intercept the request during connection establishment phase. The interceptor (in your case the AuthenticationInterceptor) should authenticate such requests and if the request is invalid, it can log the necessary entries and just reject to process any communication further from this rejected client/session.

We have many benefits of having a RequestInterceptor:

  1. It helps us to validate the incoming request at a very early phase.

  2. It can help us to build custom authenticators or rerouting components.

  3. It blocks any further message processing during request phase itself which is very important to keep the unnecessary load away from the WCF Service/Server.

Message Inspectors: The MessageInspectors can be treated as part of second phase of client-server communication when a Request is validated and connection is well established and thus it's the time when client-server has to started communicating by passing messages to each other. Now, in your application environment it could be possible that the messages pass using a binary, xml or json serialized format. There could be applicable encryptions.

An example is, it is possible that a message arrives from client A and given to Server B now server Queues it up to another Server C which can wait for some more information from Another Server D. Once Server D provides the information, the Server C which has the message in queue further joins the raw message received from Server B and Server D, gives it to another service to deserialize and convert it to something meaningful which can be returned to server B and B returns it back to Client A.

Quite complex, right? But a multi server authentication like payments by credit card using mobile PIN somewhat works in similar manner, though could be not exactly the same, but even more complex.

In WCF, Interceptors and Inspectors can work together and their duties are different. An interceptor validates the end user/connection/rerouting and an Inspector validates/processes the message.

A few points:

  1. You can build your own message inspectors by implementing IClientMessageInspector for the client side and IDispatchMessageInspector on the server side.

  2. You can implement both of the interfaces in a single class if you are owner of both client and server components.

  3. Here, in your case it seems you need to implement IDispatchMessageInspector.

A class implementing IDispatchMessageInspector does not intercepts as I mentioned before but is meant to 'Inspect' an incoming message and any outgoing message and this Inspector can be hooked using configurations when a message arrives from the client.

Please note that by this time at Inspector levels, any message which arrives is already processed at various channel stack levels and assigned to which WCF Service will process this request. If you are using any encryption in between, then the message has already been decrypted. But, the message is not deserialized yet.

A use of having your custom Inspector is it could be possible that your system implements custom serialization format like (SWIFT/FIX protocol in banking) or another level of zip/unzip encoding etc.

This custom inspector can deserialized the data and give it to your component COMP which is actually meant to work on the deserialized data.

An IDispatchMessageInspector interface has got two methods which you need to implement:

a) AfterReceiveRequest and

b) BeforeSendReply(ref Message, Object).

AfterReceiveRequest is the method which can dezerialize the data and gives it to COMP, and BeforeSendReply is the method which again serializes the data and perform any operation on the message.

You can use behaviors to attach the MessageInspectors for every message your web service receives. Both, custom Interceptors and Inspectors are largely meant to be used in Enterprise Platform or a Highly customizable platforms.

Hope this answer helps you. You can read more on the following links (possible you have gone through the first one):

http://msdn.microsoft.com/en-us/library/ee391967.aspx

http://msdn.microsoft.com/en-us/library/aa717047(v=vs.110).aspx

Regards Kajal

like image 155
Kajal Sinha Avatar answered Sep 23 '22 13:09

Kajal Sinha