我的问题是我正在尝试创建一个'角色'并将其添加到用户。它在UserManager类的引用上出错,如下面的星号所示
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var account = new AccountController();
account.**UserManager**.AddToRole(user.Id, RoleName);
var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
return View("ManageUserRoles");
我的AccountController如下
public class AccountController : Controller
{
public UserManager<ApplicationUser, string> um = new UserManager<ApplicationUser, string>(ApplicationUser user, string key);
我也试过
public UserManager<ApplicationUser, string> um = new UserManager<>();
两者都错误地说出了前者的说法:
重载方法有一些无效的争论
后者说:
预期输入
我也试过
public UserManager<ApplicationUser, string> um = new UserManager<ApplicationUser,string>();
这给出了错误:
此方法不包含带0参数的构造函数
如何正确实现/调用/使用UserManager类?
答案 0 :(得分:0)
根据MSDN https://msdn.microsoft.com/en-us/library/dn497520(v=vs.108).aspx
UserManager具有以下构造函数定义
public UserManager( IUserStore<TUser, TKey> store)
所以当你初始化它时,你需要首先拥有IUserStore实例,如下所示
根据需要实施IUserStore
public class MyUserStore<T> : IUserStore<T> where T: ApplicationUser
{ }
创建MyUserStore的实例
MyUserStore userStore = new MyUserStore<ApplicationUser>();
将您的用户管理器设为
UserManager<ApplicationUser, string> um = new UserManager(userStore);