ModelState.IsValid 在检查有效性之前修改模型时为 false

ModelState.IsValid is false when modifying model before checking validity

我遇到的问题是我在 post 操作中修改我的模型,而不是通过表单填写它(字段是密码哈希和密码盐),原因很明显。当 post 到操作时,显然密码哈希和盐是计算值而不是用户输入的。问题是,如果我生成它们并将值分配给我的 posted 客户模型,即使属性具有值,模型状态仍然说它们是必需的。请参阅下面的代码。这是我的注册操作。

[HttpGet]
    public ActionResult Register()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Register(Customer customer)
    {

        var password = Request.Form.Get("password");
        var ConfirmPassword = Request.Form.Get("confirmpassword");

        if ((password != null && ConfirmPassword != null) && (!string.IsNullOrWhiteSpace(password)
            && !string.IsNullOrWhiteSpace(ConfirmPassword)) && password == ConfirmPassword)
        {
            //generate a password salt
            var passwordsalt = Models.Helpers.PasswordHasher.GetSalt();
            //convert it into a string that can be used again by calling the Convert.FromBase64String(string); function on what will be stored
            customer.PasswordSalt = Convert.ToBase64String(passwordsalt);
            //compute the password hash here and store it in the customer
            customer.PasswordHash = Models.Helpers.PasswordHasher.ComputeHash(password, "SHA256", passwordsalt);

        }
        else if (!Models.Helpers.ValidationLibrary.ValidatePasswordRequirements(password))
        {
            ModelState.AddModelError("", "Password must be 8 characters long, have at least one number or symbol");
        }
        else
        {
            ModelState.AddModelError("", "Password and confirm password do not match");
        }


            if (ModelState.IsValid)
        {
            //db.Customers.Add(customer);
            //db.SaveChanges();

            UserRegistration regularUser = new UserRegistration();

            regularUser.customer = customer;
            regularUser.role = new XREF_CustomerRole { Role_ID = 3, Customer_ID = customer.Customer_ID };

            Models.Helpers.Helper.createUser(regularUser);

            return Login(new UserLogin { Email = customer.Email, Password = customer.PasswordHash, RememberMe = false });
        }
        return View(customer); ;
    }

这是值的屏幕截图。

这里是模型状态值的屏幕截图 连同它们对应的键

这很正常,HTML 助手就是这样工作的。他们首先使用 POST 请求的值,然后是模型中的值。这意味着即使您在控制器操作中修改了模型的值,如果 POST 请求中存在相同的变量,您的修改将被忽略,并且将使用 POSTed 值。

ASP.Net MVC Html.HiddenFor with wrong value