22

我不知道如何为 C# 数据模型制作自定义设置器。场景很简单,我希望我的密码使用 SHA256 函数自动加密。SHA256 功能非常好用(我以前在无数项目中使用过)。

我已经尝试了几件事,但是当我运行update-database它时,它似乎在递归地做某事并且我的 Visual Studio 挂起(不要发送错误)。请帮助我了解如何在模型中默认加密密码。

用我已经尝试过的代码

public class Administrator
{
    public int ID { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password
    {
        get
        {
            return this.Password;
        }

        set
        {
            // All this code is crashing Visual Studio

            // value = Infrastructure.Encryption.SHA256(value);
            // Password = Infrastructure.Encryption.SHA256(value);
            // this.Password = Infrastructure.Encryption.SHA256(value);
        }
    }
}

种子

context.Administrators.AddOrUpdate(x => x.Username, new Administrator { Username = "admin", Password = "123" });
4

2 回答 2

46

您需要使用私有成员变量作为支持字段。这允许您单独存储值并在设置器中对其进行操作。

好资料在这里

public class Administrator
{
    public int ID { get; set; }

    [Required]
    public string Username { get; set; }

    private string _password;

    [Required]
    public string Password
    {
        get
        {
            return this._password;
        }

        set
        {  
             _password = Infrastructure.Encryption.SHA256(value);                
        }
    }
}
于 2012-10-20T14:10:04.723 回答
2

您使用的 get 和 set 实际上创建了名为get_Password()and的方法set_Password(password)

您希望将实际密码存储在私有变量中。因此,只需拥有一个由这些“方法”返回和更新的私有变量就是要走的路。

public class Administrator
{
public int ID { get; set; }
[Required]
public string Username { get; set; }
[Required]
private string password;
public string Password
{
    get
    {
        return this.password;
    }

    set
    {
        this.password = Infrastructure.Encryption.SHA256(value);
    }
}
}
于 2012-10-20T14:10:36.160 回答