数据注释属性在ASP Net Core中不起作用 [英] Data annotations attributes not working in asp net core

查看:50
本文介绍了数据注释属性在ASP Net Core中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP Net core 2.2应用程序,数据批注属性[必需]根本不起作用.根据docs https://docs.microsoft.com/zh-CN/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.1#remarks .如果属性为null,包含空字符串(")或仅包含空格字符,则会引发验证异常.但是,在我的应用程序中不是这种情况.

ASP Net core 2.2 application, data annotations attributes [Required] is not working at all. According docs https://docs.microsoft.com/en-ca/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=netframework-4.7.1#remarks . A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters. However, it's not the case in my application.

        [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时.我期望是错误的.

When I'm sending request via Postman and do not specify query string value and/or form data source ModelState.IsValid is true. I'm expecting false.

推荐答案

我找出了问题的根源.我包括了.AddMvcCore,默认情况下根本不包括DataAnnotations.

I figured out the source of a problem. I was included .AddMvcCore, and by default it's not including DataAnnotations at all.

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

我在Startup.cs中添加了.AddDataAnnotations,它的工作原理像一个超级按钮.

I've added .AddDataAnnotations in Startup.cs and it works like a charm.

这篇关于数据注释属性在ASP Net Core中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆