How to validate parameters with message inspectors using schemas
Jason Taylor, Prashant Bansode, Carlos Farre, Madhu Sundararajan, Steve Gregersen
Use the followings steps to validate using message inspectors and schemas:
- Start with the schema created when you add a service reference inside visual studio. It is located under the service reference folder with the name of the service and XSD extension.
- If the service reference was created with svcutil.exe tool, you can create windows class project with the CSHARP file and then use the xsd.exe tool to generate the schema from the assembly: xsd.exe assembly.dll.
- Modify the schema to include schema facets to validate simple types for format type and length.
- Create a class the implements the schema validation logic. This class has to inherit from the interfaces
IClientMessageInspector and* IDispatchMessageInspector. IClientMessageInspector* is only needed if you want to do client side validation.
IDispatchMessageInspector is only needed if you want to do service side validation.
- Implement the methods IDispatchMessageInspector.AfterReceiveRequest IDispatchMessageInspector.BeforeSendReply, IClientMessageInspector.AfterReceiveReply, IClientMessageInspector.BeforeSendRequest depending if you are validating inbound or outbound
in client / service.
- Create a class that implements a endpoint behavior. This class has to inherit from interface
- Implement the methods ApplyClientBehavior and ApplyDispatchBehavior depending if you are doing client and/or service side validation. Add the inspectors in with clientRuntime.MessageInspectors.Add in
ApplyClientBehvior and/or DispatchRuntime.MessageInspectors.Add in ApplyDispatchBehavior
- Create a class that implements custom behavior element. This class has to inherit from
BehaviorExtensionElement. This will allow adding the custom behavior to the configuration tool.
- Add the Custom Behavior to the Configuration File. Insert the custom extension inside the WCF configuration file, so it can be used by the service
MySchemaValidationClass, Version=22.214.171.124, Culture=neutral, PublicKeyToken=null" />
- Create an Endpoint Behavior and Map it to Use the Custom Behavior. This will allow the endpoint behavior to use the schema valiation
- Configure the Service Endpoint to Use the Endpoint Behavior. This will allow the service endpoint to be configured with the endpoint behavior
<endpoint address="" behaviorConfiguration="MyEndPointBehavior"
<dns value="localhost" />