Learn to Create Interceptors in WCF Services | CodeGuru

Learn to Create Interceptors in WCF Services

Windows Communication Foundation (WCF) is a distributed system technology, which can be customized to any level as far as I have seen. A WCF application can be customized right from the protocols it uses until the size of the message. Also it allows you to host the service on multiple end points, each using a […]

Written By
CodeGuru Staff
CodeGuru Staff
Apr 20, 2012
2 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Windows Communication Foundation (WCF) is a distributed system technology, which can be customized to any level as far as I have seen. A WCF application can be customized right from the protocols it uses until the size of the message. Also it allows you to host the service on multiple end points, each using a different binding. For example a service can be exposed through HTTP as well as TCP. In this article I will cover another useful extensibility feature that can be used to intercept the WCF request during pre or post method invocation.

Interceptors with Client and Dispatch Runtimes

In WCF there are two main components called the Client and Dispatch runtimes. The client runtime does the job of converting the method calls into messages, which will be transported to a WCF service and the dispatch runtime is the one that converts the incoming message to a method call and invokes the specific WCF operation. Both of these runtimes expose a few stages, which can be extended to perform a custom operation.

An interceptor is a component, which can be plugged into any of the stages of client or dispatch runtimes. Below are a few interceptors.

1. Parameter Inspector – To inspect or modify parameter values.
2. Message Inspector – To inspect or modify the message itself.
3. Message Formatter – To format the message based on the needs.
4. Operation Selector – To select a particular operation to be invoked.

In this article I will show you how to implement a parameter inspector and add it to a behavior in order to get the parameter inspector to become a part of the Dispatch Runtime flow.

Creating Parameter Inspector

Add a new class to the WCF service, name it ParameterValidator and implement the interface IParameterInspector, which lies under the namespace System.ServiceModel.Dispatcher. In the BeforeCall method write the code to perform the parameter validation.  The reason for choosing the BeforeCall method is that the parameter validation has to be done before the operation is invoked. Below is the code.

namespace ParameterInspectionSample
{
    public class ParameterValidator : IParameterInspector
    {
        #region IParameterInspector Members
 
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
        }
 
        public object BeforeCall(string operationName, object[] inputs)
        {
            if (Convert.ToDateTime(inputs[0]) <= DateTime.Now)
                throw new FaultException("Data should be in future!");
            if (Convert.ToString(inputs[1]).Length > 50)
                throw new FaultException("Name should be less than 50 characters!");
 
            return null;
        }
 
        #endregion
    }
}
 
Advertisement

Implementing a Custom Behavior

In order to place the interceptor to use we need to create a custom behavior and apply the interceptor to it. In our case we need to create a Custom Operation behavior as the data validation holds good only for a particular operation contract. Create a class named CustomDataOperationBehavior, inherit for the class Attribute and also implement the interface IOperationBehavior. In the ApplyDispatchBehavior method create the instance of the ParameterValidator class and add it to the dispatchOperation.

namespace ParameterInspectionSample
{
    public class CustomDataOperationBehavior : Attribute, IOperationBehavior
    {
        #region IOperationBehavior Members
 
        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }
 
        public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
        {
        }
 
        public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
        {
            dispatchOperation.ParameterInspectors.Add(new ParameterValidator());
        }
 
        public void Validate(OperationDescription operationDescription)
        {
        }
 
        #endregion
    }
}
 

I have created this as an attribute so that the respective operation contract can be decorated with this class as shown below.

namespace ParameterInspectionSample
{
    [ServiceContract]
    public interface IService1
    {
        [CustomDataOperationBehavior]
        [OperationContract]
        string ProcessData(DateTime renewalDate, string name);
    }
}

I will leave it to the readers to explore the other inspectors. I hope this article was informative about the WCF extensibility.

Happy reading!

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.