I am trying to validate the WCF
service request using System.ComponentModel.DataAnnotations.dll
of Version v4.0.30319. I am using VS2010
From msdn:
The System.ComponentModel.DataAnnotations namespace provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls.
Attributes from that namespace are not handled out-of the box by WCF. You have to write Your own logic to achieve this.
Here is an article describing custom validation of parameters for WCF.
Fortunately others have already done this so here is a CodePlex project that combines WCF and Data Annotation classes. This is probably what You need.
Edit:
DataMember.IsRequired
indicates that given member must be present in the model. Not that it must have a value.
This is for your api versioning.
For example You could have had in Your Service version 1 a model like this:
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
}
This would serialize to (in simplified way):
<User>
<Id>19</Id>
</User>
And any client that was integrated with Your service would send You xml like this.
But then You changed Your model in Your version 2 to:
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public String Name { get; set; }
}
But Your client knows nothing about new version and sends You old xml. That xml will deserialize properly to Your new model but with Name
equals null.
To inform Your old clients about this change You would add IsRequired=true
to Your Name
property. That way WCF will return an error for old xml and will accept only this structure:
<User>
<Id>19</Id>
<Name>Some Name</Name>
</User>
Please not that this will not make something like this invalid:
<User>
<Id>0</Id>
<Name />
</User>
Which is what is happening in Your case. Id
is not nullable so it has a default value of 0.
And Name
is serialized as having no value - not as "not being there".