【问题标题】:String is empty but ModelState is still valid with various annotations to make it invalidString 为空,但 M​​odelState 仍然有效,各种注释使其无效
【发布时间】: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


【解决方案1】:

我不确定模型状态是否适用于您的模型集合。你能试试这个。 伪代码:

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

【讨论】:

  • 同样的结果。模型仍然有效。
  • 即使您删除所有注解并添加您自己的自定义注解“EnsureNotEmptyAttribute”。当您迭代每个模型时,您会看到什么。你的方法是否被命中,这个模型的 TryValidateModel 的结果是什么。
  • 我的注释没有被触发并且 testModelList.Any(model => !TryValidateModel(model)) 是 false,这意味着 TryValidateModel(model) 返回 true
  • 我总是用一个项目进行测试,我还重新安排了我的代码,使其接受一个 TestDto 对象作为参数,但它不起作用。
【解决方案2】:

问题是在我的 startup.cs 中我添加了 MvcCore 而不是一般的 Mvc。差异描述为here。我只需要添加 DataAnnotations,它终于奏效了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2015-06-21
    • 2014-09-12
    • 2014-03-04
    • 2019-02-11
    相关资源
    最近更新 更多