字符串为空,但ModelState仍然有效,并带有各种注释,使其无效

时间:2018-07-10 10:16:02

标签: c# validation asp.net-core .net-core modelstate

使用.NET core 2.1,我在模型上尝试了各种DataAnnotations,但当Title属性为空字符串时,一切仍然有效。我也彼此独立地尝试了它们。

True

这是我的控制器:

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");
    }
}

哪个也不起作用。可能导致什么?它只是忽略了我的注释。如果Title为null,则ModelState无效,但我也需要ModelState对于空字符串也无效。

2 个答案:

答案 0 :(得分:0)

我不确定modelstate是否适用于您的模型集合。你可以试试这个吗 伪代码:

 if (testModelList.Any(model => !TryValidateModel(model)))
 {   
     return HttpStatusCode.BadRequest;
 }

答案 1 :(得分:0)

问题是在我的startup.cs中,我通常添加MvcCore而不是Mvc。描述差异here。我只需要添加DataAnnotations就可以了。

相关问题