ASP.net身份 - UserManager <tuser>如何访问角色?</tuser>

时间:2014-01-23 22:59:20

标签: asp.net-identity user-management account-management

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

UserManager类仅在构造函数中包含IUserStore<TUser>。它没有我想象的IUserRoleStore<TUserRole>,以确定是否UserManager.IsInRoleAsync(string, string)

我认为UserStore的实现也会有一个IsInRoleAsync(string, string)函数(然后它才有意义),但事实并非如此。

另一个奇怪的事情 - 如果UserManager在其实现中知道所有内容,我们将如何处理IUser - 只有string Id和{{1作为属性?

1 个答案:

答案 0 :(得分:6)

好吧,经过大量挖掘和幸运发现 - 事实证明,Microsoft.AspNet.Identity.Core附带了一些其他接口,特别是IUserRoleStore<TUser>IUserPasswordStore<TUser> 这两个接口“继承“(实施)IUserStore&lt; TUser&gt;

因此,如果我们想要角色管理功能,我们会实施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.
    */
}

现在我们可以将MyUserStore传递给UserManager<TUser>,因为MyUserStoreIUserRoleStore<TUser>,这是IUserStore<TUser>

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

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

我希望你发现这很有用,因为大多数文档(MVC教程等)并没有告诉我们这个细节。他们告诉我们使用Microsoft.AspNet.Identity.EntityFramework的UserStore<TUser>实现 - 我们所要做的就是传入一个自定义User对象(实现IUser)和我们'很高兴去。