patricgh
patricgh

Reputation: 403

WCF DataContract validation

I'm wondering if there is any data annotation which can be added to a DataMember in a DataContract, in terms of validation.

Let's say we have a firstname(string) datamember which we do not want to be more than 50 characters in length. Is there any way to catch it or do we need to implement a custom faultexception to throw an excpetion if the length of firstname is more that 50.

We need this validation for WCF security. Any suggestion on this?

Upvotes: 2

Views: 3483

Answers (1)

Chris Dickson
Chris Dickson

Reputation: 12135

There is no feature of the DataContractSerializer which allows you to specify validation declaratively by annotating DataMembers.

If you define your DataMember as a Property (as opposed to a Field), then you can write code to validate the data during deserialization, in the property setter. The code can throw an exception on validation failure or change the data (e.g. to truncate it to 50 characters in your example of a first name member).

[DataMember]
public string FirstName
{
  get { return ...; }
  set { if (value.Length > 50) throw new MyValidationException(); }
}

Upvotes: 1

Related Questions