如何编辑FormCollection值,然后将TryUpdateModel与已编辑的集合一起使用? [英] How do I edit a FormCollection value, and then use TryUpdateModel with the edited collection?

查看:98
本文介绍了如何编辑FormCollection值,然后将TryUpdateModel与已编辑的集合一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MVC5以明文形式存储我的密码.我不想使用默认的哈希算法,因为需要 使用e.Encrypt()代替.我正在创建注册功能,我需要知道如何使用TryUpdateModel之前从FormCollection编辑值.

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.

代码如下:

    [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.

我已经尝试过:

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

...并且可以编译,但是在调试时,永远不会设置该值. e.Encrypt()确实可以用作功能,所以不是那样.

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

我在做什么错了?

推荐答案

经过反复试验,我发现了这一点:

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();
    }

但是,弹出另一个问题,DataValidationError.问题出在UserModel.cs类中:

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.

这篇关于如何编辑FormCollection值,然后将TryUpdateModel与已编辑的集合一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆