How do I edit a FormCollection value, and then use

2019-09-19 04:16发布

问题:

MVC5 is storing my passwords in plaintext. I don't want to use the default hashing algorithm, as I'm required to use e.Encrypt() instead. I'm creating a registration function, and I need to know how I can edit values from FormCollection before using TryUpdateModel.

Here's the code:

    [HttpPost]
    public ActionResult Register([Bind(Include = "User,Pass,Email")] FormCollection form)
    {
        var user = new Users();
        string Hash = e.Encrypt(form["Pass"]); // Gets set.
        if (TryUpdateModel(user, form))
        {
            context.Entry(user).State = EntityState.Added;
            context.SaveChanges();
            return RedirectToAction("Login", "Account");
        }
        return View();
    }

I've searched high and low, and everything I've found is irrelevant to my needs.

I've tried this:

form["Password"] = e.Encrypt(form["Password"])

...and that compiles, but when debugging, the value never gets set. e.Encrypt() does work as a function, so it's not that.

What am I doing wrong?

回答1:

I figured it out after some trial and error:

    [HttpPost]
    // Remove FormCollection and replace with UserModel.
    public ActionResult Register([Bind(Include= "Username,Password,EmailAddress")] UserModel user)
    {
        if (TryUpdateModel(user))
        {
            // Set password in TryUpdate success.
            user.Password = e.Encrypt(user.Password);; // Set correctly

            context.Entry(user).State = EntityState.Added;
            context.SaveChanges();
            return RedirectToAction("Login", "Account");
        }
        return View();
    }

However, another issue popped up, DataValidationError. The issue is from the UserModel.cs class:

    [RegularExpression(RegexPassword, ErrorMessage = ErrorPassword)]

I had a regular expression which didn't match the hash, so when I tried to update, it was unable to validate. That's a problem for another thread, but I just removed it for now.