Validating WCF Service Messages with Validation Application Block - Part 1
This post is one of a post series about WCF Integration in Enterprise Library 3.0.
This is the first post that I am writing about the integration between Windows Communication Foundation and Validation Application Block in Enterprise Library 3.0. This post will focus on what you should do in order to declare the validation on parameters of service operations.
When you want to make sure that the service operation receives valid parameters, you can achieve that in two ways:
1. Validating Parameters on a service operation
If your service operation received parameters with primitive types, such as:
[OperationContract]
int CreateOrder(string currency, double amount);
and you still want to validate them, you can use the parameter-level validation in the service contract:
[ServiceContract]
public interface IOrdersService
{
[OperationContract]
int CreateOrder(
[NotNullValidator] string currency,
[RangeValidator(1.0, RangeBoundaryType.Inclusive, 2.0, RangeBoundaryType.Inclusive)] double amount);
}
Notice the usage of the validation attributes before each of the parameters of the service operation.
2. Validating Message Contracts or Data Contracts passed to a service operation
If your service operation received Data Contract parameter or a Message Contract parameter, you actually use the validation logic specified above them. For example, this a Data Contract of order data that has validation logic that make sure that the input currency is one of a pre-defined domain of values.
[DataContract]
public class OrderData
{
[DataMember]
public double Amount
{
get { return amount; }
set { amount = value; }
}
[DataMember]
[DomainValidator("USD","EUR","JPY")]
public string Currency
{
get { return currency; }
set { currency = value; }
}
}
Now, when you use it in a service contract definition, you don't have to specify the validation for the input parameters, since it will be taken from the Data Contract definition.
[OperationContract]
OrderInfo CreateOrder(OrderData orderData);
Keep in mind that in order to validate an object, using attributes is not the only way to do so. If you need more flexibility you can do it using the configuration file.
In this post I talked about what you have to do in order to define what kind of parameters validation you want to achieve in your WCF service operations. In the next post I will talk about what happens when the parameters are not valid.
Enjoy!