Data annotations on WCF service contracts

南楼画角 提交于 2019-12-22 05:42:45

问题


I have a WCF service that has a [DataContract] class defined in it. Each of the properties has the [DataMember] attribute and I have added a couple of Data Annotation attributes [Required] and [StringLength] to a couple of the properties.

I then consume this service in an asp.net MVC application as a service reference. When I get a list of all the attributes using

var attr= from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                        from attribute in prop.Attributes.OfType<ValidationAttribute>()
                        select attribute;

I see none of the data annotations have come through. Is this a limitation of WCF or am I doing something fundamentally wrong here?


回答1:


The attributes will not be serialized when your data contract in sent over the wire. The new attribute that you have created in esentially meta data that is associated with the property and therfore the Type in which the property belongs to. This is not data and will not be available.

I guess that you have added a service reference in your asp.net mvc application, this will, unless specified, create new proxy classes that represent your data contract.

When you add the service reference, if you click on the advanced button make sure that the 'Use existing types' is checked. This ensure that your service will use your existing conract.

This may not be best practice because the client application will have to have knowledge about the Type you are returning from the service. This may be okay if your service is only used by yourself in which case you will need to add a reference to you contract in your asp.net mvc application.




回答2:


The OData team is working in a solution to expose the validation metadata as "vocabularies".

More information: http://www.odata.org/blog/vocabularies



来源:https://stackoverflow.com/questions/822328/data-annotations-on-wcf-service-contracts

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