繁体   English   中英

ASP.NET 标识:ApplicationUserRole 的附加属性

[英]ASP.NET Identity: Additional properties to ApplicationUserRole

我向ApplicationUserRole添加了一个附加属性,如下所示:

public class ApplicationUserRole : IdentityUserRole<int>
    {
        public string RoleAssigner { get; set; }
    }

现在我要为用户分配一个角色,如下所示:

[HttpPost]
    public ActionResult Create(UserRoleViewModel userRoleViewModel)
    {
        if (ModelState.IsValid)
        {
            using (var context = new ApplicationDbContext())
            {
                var userRole = new ApplicationUserRole
                {
                    UserId = userRoleViewModel.UserId,
                    RoleId = userRoleViewModel.RoleId,
                    RoleAssigner = userRoleViewModel.RoleAssigner
                };
                context.ApplicationUserRoles.Add(userRole);
                context.SaveChanges();
                return RedirectToAction("Index");
            }               
        }
        return View(userRoleViewModel);
    }

这工作正常!!

在添加额外的“RoleAssigner”属性之前,我可以使用AddToRoles()方法为用户分配角色,如下所示:

[HttpPost]
    public ActionResult Create(UserRoleViewModel userRoleViewModel)
    {
        if (ModelState.IsValid)
        {      
             UserManager.AddToRoles(userRoleViewModel.Id,   userRoleViewModel.RoleName);
            return RedirectToAction("Index");
         }

        return View(userRoleViewModel);
    }

我的问题是:在添加诸如“RoleAssigner”之类的附加属性后,是否有任何方法可以使用AddToRoles()方法将角色分配给用户,该方法还会在数据库中为“RoleAssigner”列插入额外的“RoleAssigner”值。

使用工作示例进行编辑:

我认为您可以通过在 IdentityConfig 中创建扩展方法来做到这一点。 我做了类似的事情,通过用户名或电话号码查找用户

根据我的理解,您想调用 UserManager.AddToRoles(...) 并填充新的角色属性。

要做到这一点(类似于之前的示例),您需要对用户管理器进行扩展。 你这样做:

public static class UserManagerExtens
{
    public static IdentityResult AddToRole(this ApplicationUserManager userManager,string userId,string[] roles,string assigner)
    {
        try
        {
            ApplicationUserRole role = null;
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                foreach (var item in roles)
                {
                    role = new ApplicationUserRole();
                    role.UserId = userId;
                    role.RoleAssigner = assigner;
                    role.RoleId = item;
                    context.AspNetUserRoles.Add(role);
                }
                context.SaveChanges();
            }
            return new IdentityResult() { };
        }
        catch (Exception ex)
        {
            return new IdentityResult(ex.Message);
        }
    }
}

这是一个工作示例,使用 UserManager 您可以使用定义的参数调用它,例如:

string[] roles = new string[] { /*your roles here*/ };
UserManager.AddToRole(/*UserIdHere*/, roles, /*assigerId here*/);

与此类似,您可以实现 UserManager 的异步或其他方法。

如果您在 startup.cs 中使用 asp.net 核心应用程序,您应该注入正确的商店模型

services.AddIdentity<ApplicationUser, YOURROLEMODEL(ApplicationUserRole )>()

如果您使用的是 asp.net 应用程序,则应该有IdentityConfig.cs文件您应该实现您的UserStore ,这将使您的 RoleModel 成为通用的。 您可以看到我创建了AppUserStore类,它获取MyIdentityRole模型作为通用类型。 并将 ApplicationUserManager 更改为使用我的AppUserStore类。

 public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new AppUserStore(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

public class AppUserStore :
    UserStore<ApplicationUser, MyIdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<ApplicationUser>
{
    public AppUserStore(DbContext context) : base(context)
    {
    }
}

public class MyIdentityRole : IdentityRole
{
    public string MyProperty { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM