【问题标题】:ASP.NET Identity: Additional properties to ApplicationUserRoleASP.NET 标识:ApplicationUserRole 的附加属性
【发布时间】:2016-10-16 09:58:59
【问题描述】:

我已向 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" 值。

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-identity


    【解决方案1】:

    编辑工作示例:

    我认为您可以通过在 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 方法。

    【讨论】:

    • 请仔细阅读整个问题..我真正想要的在我的问题的最后一段中说!
    • 谢谢!! AddToRole() 扩展方法中作为参数的附加属性在哪里?请根据我的代码写出AddToRole()方法的完整实现...希望对我有更大的帮助!!
    • 现在你有一个具体的例子。
    • @TanvirArjel 你试过确切的例子吗?如果它有效,请将其标记为正确或提供一些反馈,以便其他有类似问题的用户可以使用它。
    【解决方案2】:

    如果您在 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; }
    }
    

    【讨论】:

    • 无法理解!!你能举个例子给我解释一下吗??
    • @TanvirArjel 你在使用 asp.net 核心应用程序吗?
    • @TanvirArjel 我也更改了答案以涵盖该案例
    • @TanvirArjel 抱歉,我没有很好理解问题,我展示了如何替换您的 RoleModel 而不是 UserRoleModel,现在我将更正
    • 感谢大家的辛勤工作!!您在此处编写的内容与我的 IdentityConfig.cs 文件代码相同。所以没有问题...我的问题是:现在如何修改 AddToRoles() 方法,该方法还将附加属性值与 UserID 一起插入数据库和 RoleId。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2014-04-10
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多