Data Annotation attributes are not firing in WCF

这一生的挚爱 提交于 2019-11-29 08:39:06

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!