我正在使用 Asp.Net Identity 2.2.1。
我实现这一点的方法是创建我自己的用户:
public class MyUser : IUser {...}
然后创建我自己的UserStore:
(实现您实现的接口所需的所有方法,并在这些方法上使用您的数据访问来提取/插入数据。例如,我创建了另一个我使用的 dal 类dapper https://github.com/StackExchange/dapper-dot-net为了访问数据库,我在我的用户存储中提供了一种方法的示例,但对于您实现的所有其他方法来说,这是相同的想法)
public class MyUserStore : IUserStore<MyUser>, IUserPasswordStore<MyUser>, IUserLockoutStore<MyUser, string>, IUserEmailStore<MyUser>
{
public Task<MyUser> FindByNameAsync(string userName)
{
MyUser muser = dal.FindByUsername(userName);
if (muser != null)
return Task.FromResult<User>(muser);
return Task.FromResult<MyUser>(null);
}
//... all other methods
}
然后我的 dal.cs 上的方法看起来像这样:
public MyUser FindByUsername(string username)
{
//pull user from the database however you want to based on the username,
//in my case here is where I used Dapper to query the db and return the User object with the data on it, but you can do it however you want.
return myUser; //object with data on it
}
然后在我的 UserManager 上我设置用户存储如下:
public UserManager() : base(new MyUserStore())
{
//anything else you need on the constructor
}
NOTE:
并非 MyUserStore 上的所有方法都需要访问数据库,因为其中很多方法都调用 FindUser... 方法或 UpdateUser 方法。例如:
public Task<int> IncrementAccessFailedCountAsync(MyUser user)
{
//here I just updated the user object as I know that UpdateAsync() method will be called later.
return Task.FromResult<int>(++user.FailedAttempts);
}