WCF服务合同上的数据注释 [英] Data annotations on WCF service contracts

查看:49
本文介绍了WCF服务合同上的数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WCF服务,其中定义了[DataContract]类。每个属性都具有[DataMember]属性,并且我向几个属性添加了两个[数据注释]属性[Required]和[StringLength]。



I然后在asp.net MVC应用程序中使用此服务作为服务引用。当我从TypeDescriptor.GetProperties(instance)中的prop中使用

  var attr =获取所有属性的列表时,Cast< PropertyDescriptor> ;()
来自prop.Attributes.OfType< ValidationAttribute>()
选择属性中的属性;

我没有看到任何数据注释。这是WCF的限制吗?还是我在这里做根本上错误的事情?通过电线发送。您在本质上是与属性以及属性所属的类型关联的元数据中创建的新属性。这不是数据,将不可用。



我想您已经在asp.net mvc应用程序中添加了服务引用,除非指定,否则它将创建新的代表您的数据合同的代理类。



添加服务参考时,如果单击高级按钮,请确保选中使用现有类型。这确保您的服务将使用您现有的约定。



这可能不是最佳做法,因为客户端应用程序必须具有有关您从服务返回的类型的知识。如果您的服务仅由您自己使用,这可能是可以的,在这种情况下,您需要在asp.net mvc应用程序中添加对合同的引用。


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?

解决方案

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.

这篇关于WCF服务合同上的数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆