How do I edit a FormCollection value, and then use

2019-09-19 03:54发布

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条回答
手持菜刀,她持情操
2楼-- · 2019-09-19 04:21

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.

查看更多
登录 后发表回答