Validation of WCF Requests with the Enterprise Library Validation Block

In order to enable validation of the properties of a request message, you only need to add a [ValidationBehavior] attribute to your service interface, just next (or before) the [ServiceContract], and a [FaultContract(typeof(ValidationFault))] on the method declaration. The ValidationBehaviorAttribute and ValidationFault classes are defined in the Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF assembly and are part of the Validation Application Block of the Enterprise Library 4.1, more specifically, of the WCF integration module.

Here is an example:



public interface IRequest




    SomeResponse DoSomething(SomeRequest req);


 In your request class (data transfer objects), you must then add validation attributes for each of the properties that you want to validate. For example:


public class SomeRequest


    [NotNullValidator(MessageTemplate = "{1} is null")]  //the property cannot be null

    [StringLengthValidator(4, 40, MessageTemplate = "The {1} must have between 4 and 40 characters")]  //must have between 4 and 40 characters

    [ContainsCharactersValidator("_/\\.;,:\'\"", ContainsCharacters = Any, Negated = true,  MessageTemplate = "The {1} contains invalid characters")]  //may not contain '_', '/', '\', '.', ';', ':', '\'' or "\"' characters

    public String Name

        get; set;

Notice the {1} placeholder on the MessageTemplate property value: it is replaced by the current validating member name, in this case, the Name property. Valid placeholders depend on the actual validator used, but there are some common ones, which are:

  • {0}: The current value of the field or property
  • {1}: The name of the field or property
  • {2}: The tag name

Also, you can have resource values instead of hardcoded strings; instead of the MessageTemplate, add MessageTemplateResourceName and MessageTemplateResourceType, and the error string will be obtained from the resource named MessageTemplateResourceName from the assembly that contains the MessageTemplateResourceType type.

Your requests will then be automatically validated before they are transmitted, and, in the case of a validation exception, you will receive a FaultException<ValidationFault>, from which you will be able to extract validation errors, through the Details list property.

In the next post, I will explain how you can add validation to ASP.NET forms from the same metadata that is defined on the data transfer object class.

Bookmark and Share



Comments have been disabled for this content.