ASP.NET标识:ApplicationUserRole的其他属性

时间:2016-10-16 09:59:00

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

我已向 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() <为用户分配角色? / strong>方法,它还会在数据库中为“RoleAssigner”列插入额外的“RoleAssigner”值。

2 个答案:

答案 0 :(得分: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可以使用definded调用它 参数如:

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

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

答案 1 :(得分:0)

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