无论DataAnnotations属性如何,ModelState.IsValid始终为true [英] ModelState.IsValid always true, regardless of DataAnnotations attributes

查看:81
本文介绍了无论DataAnnotations属性如何,ModelState.IsValid始终为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Visual Studio 2015中使用了新的MVC6框架,突然所有的数据注释都停止工作了.所有这些,无需我更改代码.

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

    ...
}

还有

[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 
    }
}

为什么在地球上,我是否通过了"ModelState.IsValid"测试(该评估始终为true)?

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

例如,我正在传递Name ="x",但它仍然评估为true.好像没有注释.

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

这与使用MvcCore有关吗?

Does it relate to using MvcCore ?

推荐答案

令人沮丧的是,我忘记了更改为核心"项目会剥夺许多常见功能.因此,在Startup.cs中,添加

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()

  • services.AddMvcCore().AddDataAnnotations()

取决于您的用法.

这篇关于无论DataAnnotations属性如何,ModelState.IsValid始终为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆