【问题标题】:Data annotations attributes not working in asp net core数据注释属性在 asp net core 中不起作用
【发布时间】:2019-09-05 14:29:05
【问题描述】:

ASP Net core 2.2 应用程序,数据注释属性 [必需] 根本不起作用。根据文档https://docs.microsoft.com/en-ca/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.1#remarks。 如果属性为 null、包含空字符串 ("") 或仅包含空白字符,则会引发验证异常。 但是,在我的应用程序中并非如此。

        [HttpPost]
        public IActionResult TranslateHtml(
            [FromQuery] [Required] int value,
            [FromForm] [Required(AllowEmptyStrings = false)]
            string source)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            return Ok();
        }

当我通过 Postman 发送请求并且未指定查询字符串值和/或表单数据源时,ModelState.IsValid 为 true。我期待的是假的。

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    我找到了问题的根源。我被包含在 .AddMvcCore 中,默认情况下它根本不包含 DataAnnotations。

    services.AddMvcCore()
            .AddDataAnnotations()
            .AddCors()
            .AddJsonFormatters()
    

    我在 Startup.cs 中添加了 .AddDataAnnotations,它就像一个魅力。

    【讨论】:

      猜你喜欢
      • 2016-04-07
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      相关资源
      最近更新 更多