.NET 框架使用什么类从类中提取数据注释信息?
我遇到一种情况,需要从 ASP.NET ViewModel 中提取数据注释信息,以便执行一些更高级的验证。
我想知道是否可以使用本机类型描述符类,而不是编写自己的类型描述符类。
尽管数据注释与 ASP.NET MVC 无关,但如果有一些 ASP.NET MVC 特定的实现,那对我来说就不成问题。
有什么想法吗?
I have a situation in which I need to extract Data Annotations information from an ASP.NET ViewModel in order to perform some more advanced validations.
Instead of writing my own type descriptor class, I wonder if I can use the native one.
Even though Data Annotations are not tied to ASP.NET MVC, if there is some ASP.NET MVC specific implementation, that wouldn't be a problem to me.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数据注释只是普通属性,可以使用属性的普通反射机制来访问。
请参阅 MSDN 上的
访问自定义属性
和< a href="http://oreilly.com/catalog/progcsharp/chapter/ch18.html" rel="nofollow">C# 编程第 18 章。Data annotations are just normal attributes and can be accessed using the normal reflection mechanisms for attributes.
See
Accessing Custom Attributes
on MSDN and Chapter 18 of Programming C#.命名空间 System.ComponentModel.DataAnnotations 包含类 Validator 用于验证用 ValidationAttributes 修饰的对象或对象的属性。
我认为这个类被依赖于验证逻辑的框架的大部分部分(ASP.NET MVC、WCF RIA 服务等)使用。
如果您想扩展基本验证功能,您可以编写自己的 ValidationAttributes 并让 Validator 检查您的对象。
The namespace System.ComponentModel.DataAnnotations contains the class Validator which is used to validate an object or property of an object that is decorated with ValidationAttributes.
I think this class is used by the most parts (ASP.NET MVC, WCF RIA Services, etc.) of the framework that rely on Validation logic.
If you want to extend the basic validation functionality you could write your own ValidationAttributes and let the Validator check your objects.
正如我怀疑的那样,ASP.NET MVC 确实创建了一个名为 ModelMetadata 从模型中提取元信息,考虑数据注释属性。请参阅示例:
这减少了基本场景下手动读取数据注释属性的需要。
As I suspected, ASP.NET MVC did create a helper to class called ModelMetadata to extract meta information from model, considering data annotation attributes. See the example:
This reduces the need of manually reading the data-annotation attributes for the basic scenarios.