gpt4 book ai didi

asp.net-identity - ASP.net 身份 - UserManager 如何访问角色?

转载 作者:行者123 更新时间:2023-12-02 01:48:31 33 4
gpt4 key购买 nike

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

UserManager类只接受 IUserStore<TUser>在构造函数中。它没有 IUserRoleStore<TUserRole>我想需要访问它来确定是否 UserManager.IsInRoleAsync(string, string)或不。

我认为 UserStore 的实现会有一个 IsInRoleAsync(string, string)也能发挥作用(那么一切就有意义了),但事实并非如此。

另一个奇怪的事情 - 如果 UserManager 在其实现中只知道我们正在处理 IUser,它如何能够执行密码设置和重置? - 仅具有 string Idstring UserName作为属性?

最佳答案

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

因此,如果我们需要角色管理功能,我们可以实现 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> ,因为MyUserStoreIUserRoleStore<TUser> ,这是一个IUserStore<TUser> :

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

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

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

关于asp.net-identity - ASP.net 身份 - UserManager<TUser> 如何访问角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321103/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com