有一个数据上下文:
public class OurDbContext : DbContext, IOurDbContext, IDataProtectionKeyContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;
}
有一种方法可以实现向数据库发送数据:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateNewClient(Employee client, string TypeOfClient)
{
var secstring = _protector.Protect(client.Password);
Employee temp = new Employee
{
Name = client.Name,
Password = secstring,
RoleId = 1
};
await _mediatr.Send(new NewEmployee.NewEmployeeCommand(temp));
return Redirect("~/");
}
没有任何东西进入数据库。
如果我们从上下文类中删除实现IDataProtectionKeyContext
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;
并缩短线路
builder.Services.AddDataProtection().PersistKeysToDbContext<OurDbContext>();
前
builder.Services.AddDataProtection();
然后数据以加密密码进入数据库。但在这种情况下,5 分钟后,尝试读取此密码将由于密钥过期而导致异常。
微软的帮助没有说明这一点:
简而言之,我尝试将上下文从 PostgreSQL 更改为 MS SQL 和 Sqlite,并且使用 Microsoft 在其帮助中推荐的配置,一切都在其中运行良好。