【发布时间】:2018-07-10 10:16:01
【问题描述】:
使用 .NET core 2.1 我在模型上尝试了各种 DataAnnotations,但当我的 Title 属性为空字符串时,一切仍然有效。我也分别尝试过它们......
public class TestDto
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
[DisplayFormat(ConvertEmptyStringToNull = true)]
[StringLength(200, MinimumLength = 10, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]
public string Title { get; set; }
}
这是我的控制器:
[HttpPost]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public Task<IActionResult> PostAsync([FromBody] List<TestDto> testModelList)
{
if (ModelState.IsValid)
{
foreach (TestDto testModel in testModelList)
{
//do things
return Ok();
}
}else{
return BadRequest("ModelState invalid");
}
}
我什至尝试为我的“标题”属性创建自己的注释:
public class EnsureNotEmptyAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var stringToTest = value as String;
if (!string.IsNullOrEmpty(stringToTest))
{
return true;
}
return false;
}
}
这也不起作用。什么可能导致这种情况?它只是忽略了我的注释。当 Title 为 null 时,ModelState 无效,但我需要 ModelState 对于空字符串也无效。
【问题讨论】:
-
如何在视图中渲染模型?单独验证单个模型项和模型项列表之间存在差异。
-
@ChetanRanpariya 我使用角度 5/6。这是我的代码中发布到我的 .NET 核心项目的部分:pastebin.com/px6uZeZc 顺便说一句,我更改了变量名,因为它是私有项目,我无法显示太多
标签: c# validation asp.net-core .net-core modelstate