4

...而且我们只在 Microsoft.AspNet.Identity 中。(我们甚至没有查看 Microsoft.AspNet.Identity.EntityFramework 的基本实现。)

该类UserManager仅接受IUserStore<TUser>at 构造函数。它没有IUserRoleStore<TUserRole>我想需要访问以确定是否UserManager.IsInRoleAsync(string, string)

我在想 UserStore 的实现也会有一个IsInRoleAsync(string, string)功能(那么这一切都有意义),但事实并非如此。

IUser另一个奇怪的事情 - 如果 UserManager 在其实现中所知道的只是我们正在处理- ,它如何能够执行密码设置和string Id重置string UserName

4

1 回答 1

6

好吧,经过大量的挖掘和幸运的发现 - 事实证明 Microsoft.AspNet.Identity.Core 带有一些其他接口,特别是,IUserRoleStore<TUser>它们IUserPasswordStore<TUser> 都“继承”(实现) IUserStore<TUser>

因此,如果我们想要角色管理功能,我们实现IUserRoleStore<TUser>

class MyUser : IUser
{
        // Additional properties and functions not shown for brevity.
}

class MyUserStore : IUserRoleStore<MyUser>
{
    public bool IsInRole(string username, string role)
    {
       // Implementation not show for brevity.
    }


    /* We would then implement the rest of the required functions.

       We would have a data context here that has access to users,
       user-roles, and roles.
    */
}

现在我们可以传递MyUserStoreUserManager<TUser>, 因为MyUserStore是一个IUserRoleStore<TUser>, 这是一个IUserStore<TUser>:

UserManager<MyUser> UM = new UserManager<MyUser>(new MyUserStore());

然后,我怀疑源代码UserManager<TUser>使用反射来确定在构造函数中传递给它的存储是否实现了IUserStore<TUserStore>“子接口”之一,以便能够执行角色检查(如果它实现IUserRoleStore<TUser>)或密码集/reset(如果它实现了IUserPasswordStore<TUser>)。

我希望你觉得这很有用,因为大多数文档(MVC 教程等)都没有告诉我们这个细节。他们告诉我们使用UserStore<TUser>Microsoft.AspNet.Identity.EntityFramework 的实现——我们所要做的就是传入一个自定义User对象(实现IUser),我们就可以开始了。

于 2014-01-24T05:02:47.543 回答