问题
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