MVC5 项目模板默认没有角色管理器,
所以我们从创建角色管理器类开始;
(为了保持项目结构良好,最好添加如下所述的类):
1-创建ApplicationRole类(添加到Models文件夹下的IdentityModels.cs)
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
}
2- 创建 ApplicationRoleManager 类(将其放在 App_Start 文件夹下的 IdentityConfig.cs 中)
public class ApplicationRoleManager : RoleManager<ApplicationRole>, IDisposable
{
public ApplicationRoleManager(RoleStore<ApplicationRole> store) : base(store) { }
public static ApplicationRoleManager Create(
IdentityFactoryOptions<ApplicationRoleManager> options,
IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
}
}
3- 在应用程序启动时配置角色管理器;将以下行添加到 Startup.Auth.cs 文件中的 ConfigureAuth(IAppBuilder app) 方法:
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
4- 如果需要,创建一个新控制器或使用现有控制器,并在控制器构造函数中定义 ApplicationuserManager 和 ApplicationRoleManager 的参数,然后从 owin 上下文中检索身份管理器:
namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;
public class UsersAndRolesController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
public UsersAndRolesController() { }
public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
// GET: UsersAndRoles
public ActionResult Index()
{
return View();
}
}
}
现在设置已完成,控制器已准备好创建用户和角色,
为了创建用户,只需创建一个 ApplicationUser 并使用 UserManager.Create 方法添加它,密码必须与 ApplicationUserManager 类中定义的规则匹配。
5-通过调用UserManager.Create方法创建用户:
var user = new ApplicationUser
{
UserName = "Ziyad",
Email = "email@domainname.com"
};
var password = "P@ssw0rd";
UserManager.Create(user, password);
6- 使用 RoleManager 以类似的方式创建角色:
var role = new ApplicationRole
{
Name = "Students"
};
RoleManager.Create(role);
7- 最后一部分是使用 UserManager 为用户分配角色:
UserManager.AddToRole("user_id", "role_name");
完整的控制器在这里:
namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;
using Models;
public class UsersAndRolesController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
public UsersAndRolesController() { }
public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
public string CreateUser()
{
var user = new ApplicationUser
{
UserName = "Ziyad",
Email = "email@domainname.com"
};
var password = "P@ssw0rd";
var result = UserManager.Create(user, password);
if (result.Succeeded)
{
return "User created";
}
else
{
var msg = "Error, user not created";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
public string CreateRole()
{
var role = new ApplicationRole
{
Name = "Teachers"
};
var result = RoleManager.Create(role);
if (result.Succeeded)
{
return "Role created";
}
else
{
var msg = "Error, role not created";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
public string AddUserToRole()
{
var user = UserManager.FindByEmail("email@domainname.com");
if (user != null)
{
var result = UserManager.AddToRole(user.Id, "Teachers");
if (result.Succeeded)
{
return "User assigned to role";
}
else
{
var msg = "Error, user not assigned to role <br />";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
else
{
return "User not found!";
}
}
}
}
如果您想将某些视图/菜单限制为特定角色,请使用 User.IsInRole("role_name") 方法:
if (User.IsInRole("Teachers"))
{
// role specific options
}
如果您只想允许特定角色访问操作方法,请使用授权属性:
[Authorize(Roles = "Teachers")]
public ActionResult ActionName()
{
//teachers specific method
}
希望这会有所帮助:)