无法在asp.net vnext类库中使用required属性

Mar*_*ain 5 c# asp.net asp.net-mvc class-library

更新:我当然试图添加using System.ComponentModel.DataAnnotations.它不起作用.

问题:我不能Required在asp.net vnext类库项目中使用属性.

案例:
1.使用默认设置添加asp.net vnext类库项目.
2. Human使用字符串属性创建类Name.
3.添加Required属性到Name.
4.获取编译错误:

Error   CS0246  The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)  
Run Code Online (Sandbox Code Playgroud)

下面是我的project.json:

{
    "version": "1.0.0-*",
    "dependencies": {
        "System.ComponentModel.Annotations": ""
    },
    "frameworks": {
        "aspnet50": {
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Runtime": ""
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我也可以DataAnnotations在asp.net vnext中使用,但不能在vnext类库中使用.为什么?

Jar*_*lls 5

vNext Web项目依赖于Microsoft.AspNet.Mvc.这引入了一个很大的依赖树,数据注释在包下Microsoft.DataAnnotations

Microsoft.DataAnnotations添加依赖项以使用数据协定属性.

在你的project.json文件更改

"dependencies": {
    "System.ComponentModel.Annotations": ""
},
Run Code Online (Sandbox Code Playgroud)

"dependencies": {
     "Microsoft.DataAnnotations":  "1.0.0-beta1"
},
Run Code Online (Sandbox Code Playgroud)

用当前版本号替换1.0.0-beta1.Visual Studio将为您自动完成它.


为什么Microsoft.DataAnnotations工作而不是System.ComponentModel.Annotations

从一点点调查System.ComponentModel.Annotations包含两个目标

  • aspnetcore50\System.ComponentModel.Annotations.dll
  • contract\System.ComponentModel.Annotations.dll

aspnetcore50程序集适用于新的Core CLR.它包含Required属性并适用于Core CLR.

contract组件包含了所有的类型,但这些方法都是空的.这就像一个必须由框架实现的虚拟依赖.这个虚拟程序集用于.NET 4.5,这就是为什么针对.NET 4.5和Core CLR的项目都找不到该Required属性的原因.

另一方面,Microsoft.DataAnnotations程序包依赖于System.ComponentModel.Annotations但也引用了框架程序集System.ComponentModel.DataAnnotations,它在.NET 4.5上运行时实际提供了类型

我觉得这篇文章很有意思.它解释了这些合同组件在帖子结尾处的内容.http://alxandr.me/2014/07/20/the-problems-with-portable-class-libraries-and-the-road-to-solving-them/