为什么 [Required] 属性不会导致 modelState 中的错误

why [Required] attribution doesn't cause cause errors in modelState

我是 ASP.NET 核心 MVC 的新手,只是一个关于模型验证的问题。下面是我的代码:

public class HomeController : Controller
{
   public ViewResult Index([Required]string nonExistName)
        {            
           // put a debugger here
           return View();
        }
}

所以当我 运行 应用程序时,使用了默认路由,显然在查询字符串或路由值中不会有任何名为 nonExistName 的东西,因此模型绑定应该会引发错误在 ModelState.

但实际上根本没有验证错误,我设置了一个断点来检查ModelState的状态,完全没有错误。我也试过ModelState.IsValid

public class HomeController : Controller
{
   public IActionResult Index([Required]string nonExistName)
   {            
      if (ModelState.IsValid)
      {
         return View();
      }
      return NotFound();
   }
}

仍然返回正常的索引视图。

为什么 [Required] 不会导致 ModelState 出错?如果我将 [Required] i 放在模型 class 的 属性 之上,那么它将起作用。但是为什么放到action方法里就不行了?

您描述的功能称为顶级节点验证。您可以在文档中阅读更多相关信息:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1#top-level-node-validation

重要的一点是,它的工作方式会有所不同,具体取决于您使用的 ASP.NET Core 运行 版本。确保您启用了该功能,如文档中所述:

When running with CompatibilityVersion.Version_2_1 or later, top-level node validation is enabled by default. Otherwise, top-level node validation is disabled. The default option can be overridden by setting the AllowValidatingTopLevelNodes property in (Startup.ConfigureServices), as shown here:

services.AddMvc(options => 
    {
        options.AllowValidatingTopLevelNodes = true;
    })