【问题标题】:Can't use required attribute in the asp.net vnext class library无法在 asp.net vnext 类库中使用必需的属性
【发布时间】:2015-04-25 05:25:07
【问题描述】:

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

问题:我无法在 asp.net vnext 类库项目中使用Required 属性。

案例:
1.添加默认设置的asp.net vnext类库项目。
2. 使用字符串属性Name创建类Human
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?)  

下面是我的project.json:

{
    "version": "1.0.0-*",
    "dependencies": {
        "System.ComponentModel.Annotations": ""
    },
    "frameworks": {
        "aspnet50": {
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Runtime": ""
            }
        }
    }
}

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

【问题讨论】:

  • 为什么投反对票?这对我来说似乎是一个合理的问题。
  • @downvoter,请注意发布原因。

标签: c# asp.net asp.net-mvc class-library


【解决方案1】:

vNext web 项目依赖于Microsoft.AspNet.Mvc。这拉入了一个大的依赖树,数据注解在包Microsoft.DataAnnotations

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

在您的project.json 文件中更改

"dependencies": {
    "System.ComponentModel.Annotations": ""
},

"dependencies": {
     "Microsoft.DataAnnotations":  "1.0.0-beta1"
},

将 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/

【讨论】:

  • 我的问题是为什么它适用于 Microsoft.DataAnnotations 而不是 System.ComponentModel.Annotations?
  • 非常感谢。我会在晚上在家试一试(我是格林威治标准时间 +3 并且工作中没有 VS 2015)。
  • 好的,我扩展了答案来解释为什么 System.ComponentModel.Annotations 还不能工作 Microsoft.DataAnnotations。
  • 我在引用附近有一个感叹号,无法使用它screencast.com/t/RaaxXpFyCam。我对 vnext 类库的所有设置都是默认设置。以前这意味着我尝试使用带有错误 .net 框架的 dll,但我不确定当前情况。您是否刚刚将 Microsoft.DataAnnotations 添加到 vnext 类库并且一切都按预期进行?
  • 我部分地找出了感叹号的问题。 KPM 不会将任何包下载到 .kpm/packages。现在我必须弄清楚原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多