ModelState.IsValid always true, regardless of DataAnnotations attributes

↘锁芯ラ 提交于 2019-12-10 15:38:48

问题


I'm using the new MVC6 framework with Visual Studio 2015, and suddenly all my Data Annotations stopped working. All of them, without me changing the code.

public sealed class RegisterUser
{
    [Required(ErrorMessage = "required")]
    [RegularExpression(@"^((.|\n)*)$", ErrorMessage = "regex")]
    [StringLength(32, MinimumLength = 3, ErrorMessage = "length")]
    public string Name { get; set; }

    ...
}

And

[Route(Address + "/membership")]
public class MembershipController : Controller
{
    // POST [address]/membership/register
    [AllowAnonymous]
    [HttpPost("Register")]
    public IActionResult Register([FromBody]RegisterUser model)
    {
        // Validate the input model.
        if (model == null)
            return ...

        if (!ModelState.IsValid)
            return ... 

        // Always get HERE 
    }
}

Why, on earth, do I pass the "ModelState.IsValid" test (it always evaluates to true) ?

For example, I'm passing Name="x", and it still evaluates to true. As if the annotations aren't there.

Does it relate to using MvcCore ?


回答1:


Frustrating as it is, I forgot that changing to 'core' project strips out many of the common features. And so, in Startup.cs, add

  • services.AddMvc()

or

  • services.AddMvcCore().AddDataAnnotations()

Depending on your usage.



来源:https://stackoverflow.com/questions/38962288/modelstate-isvalid-always-true-regardless-of-dataannotations-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!