How do I edit a FormCollection value, and then use TryUpdateModel with the edited collection?

谁说我不能喝 提交于 2019-12-25 01:31:30

问题


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.



来源:https://stackoverflow.com/questions/29550194/how-do-i-edit-a-formcollection-value-and-then-use-tryupdatemodel-with-the-edite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!