ASP Net core 2.2应用程序,数据批注属性[必需]根本不起作用.根据docs docs.microsoft/zh-CN/dotnet/api/systemponentmodel.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 docs.microsoft/en-ca/dotnet/api/systemponentmodel.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中不起作用
发布评论