我遇到的问题是我在post操作中修改我的模型,而不是通过表单填写它(字段是密码哈希和密码盐),原因很明显。当发布到操作时,显然密码哈希和salt是用户输入的计算值。问题是,如果我生成它们并将值分配给我发布的客户模型,模型状态仍然表示即使属性具有值,它们也是必需的。见下面的代码。这是我的注册行动。
[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); ;
}
答案 0 :(得分:1)
这是正常的,它是HTML帮助程序的工作方式。他们首先使用POST请求的值,然后使用模型中的值。这意味着即使您在控制器操作中修改模型的值,如果POST请求中存在相同的变量,您的修改也将被忽略,并且将使用POSTed值。