加入角色
1. 加入角色信息到webpages_Roles表中
我们可以在Server Explorer中非常方便地加入角色信息进入webpages_Roles表,如下图所示:
然后加入信息,如下图所示,我们加入5种角色。
2. 在Controller中给注册的用户信息加入角色,需要使用到Roles.AddUserToRoles方法,具体可以参阅:
http://msdn.microsoft.com/en-us/library/system.web.security.roles.addusertoroles.aspx
在下面的例子中,我们在Register方法(位于AccountController.cs中)使用了Roles.AddUserToRoles方法(它也就是一个User, Roles, and Membership static classes ),将得到的model的role信息存入,这里需要对应model和view,关于register的model和view这里就不多写了。
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
your code…. your code
string choosenRole;
if (model.Position == 0)
choosenRole = "Admin";
else if (model.Position == 1)
choosenRole = "Planer";
else if (model.Position == 2)
choosenRole = "Controller";
else if (model.Position == 3)
choosenRole = "Manager";
else
choosenRole = "Employee";
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
your code…. your code
string choosenRole;
if (model.Position == 0)
choosenRole = "Admin";
else if (model.Position == 1)
choosenRole = "Planer";
else if (model.Position == 2)
choosenRole = "Controller";
else if (model.Position == 3)
choosenRole = "Manager";
else
choosenRole = "Employee";
System.Web.Security.Roles.AddUserToRole(model.UserName, choosenRole);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
your code … your code
return View(model);
}
使用者授权
需要使用membership的role控制这样才能使用,很简单我们使用[Authorize]修饰词
譬如
或者
[Authorize(Roles = "Admin,Manager")]
或者
[Authorize(Roles = "Manager")]
[Authorize(Roles = "Admin")]
也可以限定用户,譬如
[Authorize(User="Alex")]
譬如在HomeController.cs中:
[Authorize(Roles = "Manager")]
public ActionResult Contact()
{
ViewBag.Message = "";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "";
return View();
}
没有评论:
发表评论