asp.net core 2.0模型验证不验证数据

Ali*_*zad 8 c# model-validation asp.net-core

我正在使用ASP.NET Core 2.0默认模型验证,ModelState.IsValid尽管模型中存在错误数据,但似乎无法使用始终为真.

[HttpPost("abc")]
public async Task<IActionResult> Abc([FromBody]AbcViewModel model)
{
    if (!ModelState.IsValid) { return BadRequest(ModelState); }
    ...
}

public class AbcViewModel
{
    [Required(ErrorMessage = "Id is required")]
    [Range(100, int.MaxValue, ErrorMessage = "Invalid Id")]
    public int Id { get; set; }

    public bool Status { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

当我从Angular应用程序发布数据时,值正确映射到模型,但如果Id为"0"或小于100,则验证器RequiredRange验证器都不起作用且ModelState.IsValid始终为true.我错过了什么?

Col*_*n K 5

如果使用services.AddMvcCore(),则需要显式设置您的应用程序以使用数据注释执行验证:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore()
         .AddDataAnnotations()
         /* etc. */;
}
Run Code Online (Sandbox Code Playgroud)