数据注释属性在ASP Net Core中不起作用

编程入门 行业动态 更新时间:2024-10-27 08:26:39
本文介绍了数据注释属性在ASP Net Core中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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中不起作用

本文发布于:2023-11-15 07:05:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1592220.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   中不   属性   数据   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!