WCF服务契约上的数据注释
我有一个 WCF 服务,其中定义了一个 [DataContract] 类。 每个属性都有 [DataMember] 属性,并且我已向其中几个属性添加了几个数据注释属性 [Required] 和 [StringLength]。
然后,我在 ASP.NET MVC 应用程序中使用此服务作为服务引用。 当我使用以下命令获取所有属性的列表时,
var attr= from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
from attribute in prop.Attributes.OfType<ValidationAttribute>()
select attribute;
我发现没有任何数据注释通过。 这是 WCF 的限制还是我在这里做了一些根本错误的事情?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的数据合同通过网络发送时,属性不会被序列化。 您在本质上在与属性关联的元数据中创建的新属性,因此也与属性所属的类型关联。 这不是数据,也不会可用。
我猜您已经在 ASP.NET MVC 应用程序中添加了一个服务引用,除非指定,否则这将创建代表您的数据协定的新代理类。
添加服务引用时,如果单击高级按钮,请确保选中“使用现有类型”。 这可确保您的服务将使用您现有的合同。
这可能不是最佳实践,因为客户端应用程序必须了解您从服务返回的类型。 如果您的服务仅供您自己使用,这可能没问题,在这种情况下,您需要在 ASP.NET MVC 应用程序中添加对合同的引用。
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.
OData 团队正在开发一种解决方案,将验证元数据公开为“词汇表”。
更多信息:http://www.odata.org/blog/vocabularies
The OData team is working in a solution to expose the validation metadata as "vocabularies".
More information: http://www.odata.org/blog/vocabularies