[C#][ASP.NET MVC]实做成员和角色管理
在网站安全管理方面,ASP.NET2.0以后提供两大API(Membership、Role),
帮助开发人员快速建立相关安全管理机制,
而MVC架构下我们当然也可以利用这两大API实做管理机制,
自己觉得整体开发时间还满快的(拜MVC所赐XD),这里记录一下。
Add SystemController
公开成员相关属性
#region 成员相关属性 public class UserAttribute { public Guid key { get; set; } public String Username { get; set; } public String Lastlogindate { get; set; } } public class CreateAttribute : UserAttribute//继承UserAttribute { public String Password { get; set; } public String Confirmpw { get; set; } public String Email { get; set; } } public class DetailsAttribute : CreateAttribute//继承CreateAttribute { public String Comment { get; set; } public bool Isapproved { get; set; } public String Createdate { get; set; } public String Lastactivitydate { get; set; } public String Lastlockoutdate { get; set; } } public class EditAttribute : DetailsAttribute//继承DetailsAttribute { public bool IslockedOut { get; set; } public String Lastpasswordchangeddate { get; set; } } #endregion
?Add SystemRepository
public class SystemRepository { public ListGetAllusers() { List users = new List (); foreach (MembershipUser t in Membership.GetAllUsers()) { users.Add(//循环设定公开属性(UserAttribute class in controller) new UserAttribute { key = (Guid)t.ProviderUserKey, Username = t.ToString(), Lastlogindate=t.LastLoginDate.ToString("yyyy/MM/dd hh:mm:ss") }); } return users; } public List Detailsusers(Guid key) { List Details = new List (); var user = Membership.GetUser(key);//依照key取得成员相关资讯 Details.Add(//设定公开属性(DetailsAttribute class in controller) new DetailsAttribute { Username = user.UserName, key = (Guid)user.ProviderUserKey, Email = user.Email, Comment = user.Comment, Isapproved = user.IsApproved, Createdate = user.CreationDate.ToString("yyyy/MM/dd hh:mm:ss"), Lastlogindate = user.LastLoginDate.ToString("yyyy/MM/dd hh:mm:ss"), Lastactivitydate = user.LastActivityDate.ToString("yyyy/MM/dd hh:mm:ss"), Lastlockoutdate = user.LastLockoutDate.ToString("yyyy/MM/dd hh:mm:ss") }); return Details; } public List Editusers(Guid key) { List Edits = new List (); var user = Membership.GetUser(key);//依照key取得成员相关资讯 Edits.Add(//设定公开属性(EditAttribute class in controller) new EditAttribute { Username = user.UserName, key = (Guid)user.ProviderUserKey, Email = user.Email, Comment = user.Comment, Isapproved = user.IsApproved, IslockedOut=user.IsLockedOut, Createdate=user.CreationDate.ToString("yyyy/MM/dd hh:mm:ss"), Lastpasswordchangeddate = user.LastPasswordChangedDate.ToString("yyyy/MM/dd hh:mm:ss") }); return Edits; } }
?Index In Controller
[NonAction]//新增自订Url Routing protected RedirectToRouteResult RedirectToUserPage( MembershipUser user ) { var rvd = new RouteValueDictionary( new { controller = ControllerContext.RouteData.Values[ "controller" ], action = "Edit", key = ( Guid ) user.ProviderUserKey } ); return RedirectToRoute( rvd ); } SystemRepository systemrepository = new SystemRepository(); // GET: /System/ //[Authorize(Roles = "Administrators")]//属于Administrators才有权限 public ActionResult Index() { ViewData["Roles"] = Roles.GetAllRoles().ToList(); return View(systemrepository.GetAllusers());//指向systemrepository }
编写virtual method for role
#region virtual method for role [AcceptVerbs(HttpVerbs.Post)] public virtual ActionResult CreateRole(String name) { Roles.CreateRole(name);//建立新角色 return RedirectToAction("Index"); } public virtual ActionResult DeleteRole(String name) { Roles.DeleteRole(name);//删除角色 return RedirectToAction("Index"); } public virtual ActionResult AdduserTorole( Guid key, String roleName ) { var user = Membership.GetUser(key); Roles.AddUserToRole(user.UserName, roleName);//成员加入特定角色中 return RedirectToUserPage( user ); } public virtual ActionResult RemoveuserFromrole( Guid key, String roleName ) { var user = Membership.GetUser(key); Roles.RemoveUserFromRole(user.UserName, roleName);//移除特定角色中的成员 return RedirectToUserPage( user ); } #endregion
Add Index View
只列出须自行编写的表现层code
<%} %>
新增Guest角色
删除Guest角色
Details In Controller
public ActionResult Details(Guid key) { return View(systemrepository.Detailsusers(key)); }
Add Details View
须自行修改Details参数部分
.... ....... ........最后锁定日期: <%= Html.Encode(item.Lastlockoutdate)%>
<%=Html.ActionLink("Edit", "Edit", new { key = item.key })%> | <%=Html.ActionLink("Back to List", "Index")%>
<%} %>
Create In Controller
public ActionResult Create() { return View(); } // // POST: /System/Create [AcceptVerbs( HttpVerbs.Post )] public ActionResult Create( FormCollection collection ) { try { MembershipCreateStatus status = MembershipCreateStatus.UserRejected; MembershipUser user = null; if( collection[ "Password" ].Equals( collection[ "Confirmpw" ], StringComparison.CurrentCultureIgnoreCase ) ) { user = Membership.CreateUser( collection[ "Username" ], collection[ "Password" ], collection[ "Email" ], null, null, true, out status ); } if( status == MembershipCreateStatus.Success ) return RedirectToAction( "Index" ); else return RedirectToAction( "Error" ); } catch { return View( "Error" ); } }
编写virtual method for member
#region virtual method for member public virtual RedirectToRouteResult UnlockUser( Guid key ) { var user = Membership.GetUser(key); user.UnlockUser();//解除锁定 return RedirectToUserPage( user ); } public virtual ActionResult DeleteUser(Guid key) { var user = Membership.GetUser(key); Membership.DeleteUser(user.UserName, true);//删除成员 return RedirectToAction("Index"); } #endregion
Add Create View
新增test123成员
删除test123成员
?Edit In Controller
// GET: /System/Edit/5 public ActionResult Edit(Guid key) { var user = Membership.GetUser(key); ViewData["AllRoles"] = Roles.GetAllRoles().OrderBy(x => x).ToList(); ViewData["UsersRoles"] = Roles.GetRolesForUser(user.UserName).OrderBy(x => x).ToList(); return View(systemrepository.Editusers(key));//指向systemrepository } // // POST: /System/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit( Guid key, FormCollection collection ) { try { var user = Membership.GetUser(key); //设定白名单 UpdateModel( user, new[] { "Email", "Comment", "Isapproved" }, collection.ToValueProvider() ); Membership.UpdateUser(user);//更新 return RedirectToUserPage( user ); } catch { return RedirectToAction( "Error" ); } }
编写virtual method for password
#region virtual method for password public virtual ViewResult ResetPassword() { String userName = Request.Form["UserName"]; var user = Membership.GetUser(userName); var pwd = user.ResetPassword(null); ViewData["newpw"] = pwd; return View(); } #endregion
?Add Edit View
只列出须自行编写的表现层code
由于controller传给view含有list类型,所以实做IList泛型集合,并循环显示出相关数据。
<% var allRoles = (IList)ViewData["AllRoles"]; var usersRoles = (IList)ViewData["UsersRoles"]; %> ..... ...... <% using( Html.BeginForm( "ResetPassword", "System" ) ) { %><%} %> <%} %> <%=Html.ActionLink("Back to List", "Index") %> ?
?编辑test123
重设test123密码(实际应用上勿使用默认加密算法)
Add ResetPassword View
ResetPassword
将test123加入 Normal角色中
这样就完成了成员和角色管理功能了。
贺!一百篇达成
自己从去年8月加入点博客后,借由写博客文章提升自己,也认识了很多同好
收获说真的还不少,期望自己在往后的日子能继续持续下去,最后,先预祝大家虎年行大运。
原文:大专栏 [C#][ASP.NET MVC]实做成员和角色管理