运维开发网

[C#][ASP.NET MVC]实做成员和角色管理

运维开发网 https://www.qedev.com 2020-05-28 10:17 出处:网络 作者:运维开发网整理
[C#][ASP.NET MVC]实做成员和角色管理 在网站安全管理方面,ASP.NET2.0以后提供两大API(Membership、Role), 帮助开发人员快速建立相关安全管理机制, 而MVC架构下我们当然也可以利用这两大API实做管理机制, 自己觉得整体开发时间还满快的(拜MVC所赐XD),这里记录一下。 Add SystemController 公开成员相关属性 #region 成员相关

[C#][ASP.NET MVC]实做成员和角色管理

在网站安全管理方面,ASP.NET2.0以后提供两大API(Membership、Role),

帮助开发人员快速建立相关安全管理机制,

而MVC架构下我们当然也可以利用这两大API实做管理机制,

自己觉得整体开发时间还满快的(拜MVC所赐XD),这里记录一下。

Add SystemController

[C#][ASP.NET MVC]实做成员和角色管理

公开成员相关属性

#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

[C#][ASP.NET MVC]实做成员和角色管理

public class SystemRepository
    {      
        public List
  

 
  
  GetAllusers() { 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

[C#][ASP.NET MVC]实做成员和角色管理

只列出须自行编写的表现层code

 
角色 <% if( (ViewData["Roles"] as List ).Count > 0 ){ %>
    <% foreach( String role in (ViewData["Roles"] as List ) ){ %>
  • [<% =Html.ActionLink("删除", "DeleteRole", "System", new { name = Html.Encode(role) }, new { onclick = "return confirm(‘确定要删除吗?‘)" })%>] <% =Html.ActionLink(Html.Encode(role).ToString(), "Role", "System", new { id =Html.Encode(role) }, null)%>
  • <% } %>
<% }else{ %> 系统中未存在任何角色 <% } %> <% using (Html.BeginForm("CreateRole","System")) {%> 新角色名称:<% =Html.TextBox("name")%>
<%} %>

[C#][ASP.NET MVC]实做成员和角色管理

新增Guest角色

image image

删除Guest角色

image image

Details In Controller

public ActionResult Details(Guid key)
        {
            return View(systemrepository.Detailsusers(key));
        }

Add Details View

[C#][ASP.NET MVC]实做成员和角色管理

须自行修改Details参数部分

....
.......
........
 

最后锁定日期: <%= Html.Encode(item.Lastlockoutdate)%>

<%=Html.ActionLink("Edit", "Edit", new { key = item.key })%> | <%=Html.ActionLink("Back to List", "Index")%>

<%} %>

[C#][ASP.NET MVC]实做成员和角色管理

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

[C#][ASP.NET MVC]实做成员和角色管理

新增test123成员

image image

删除test123成员

image image

?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

[C#][ASP.NET MVC]实做成员和角色管理

只列出须自行编写的表现层code

由于controller传给view含有list类型,所以实做IList泛型集合,并循环显示出相关数据。

 
  
  <% var allRoles = (IList)ViewData["AllRoles"]; var usersRoles = (IList)ViewData["UsersRoles"]; %> ..... ...... <% using( Html.BeginForm( "ResetPassword", "System" ) ) { %> 
 
  
密码修改 <% foreach( var item in Model ) { %> <% =Html.Hidden( "Username", Html.Encode( item.Username ) )%> <% =item.Createdate != item.Lastpasswordchangeddate ? item.Lastpasswordchangeddate : "从未变更密码"%>
<%} %> <%} %>
角色修改 <% if( ( ( IList ) ViewData[ "AllRoles" ] ).Count > 0 ) { %> <% foreach( String role in allRoles ) { %> <% foreach( var item in Model ) { %> <% if( usersRoles.Contains( role ) ) { %> [<% =Html.ActionLink( "移除", "RemoveuserFromrole", "System", new { key = Html.Encode(item.key ), roleName = Html.Encode( role )}, null )%>]<% } else { %> [<% =Html.ActionLink( "加入", "AdduserTorole", "System", new { key = Html.Encode(item.key ), roleName = Html.Encode( role )}, null )%>] <% } %> <% =Html.ActionLink( role, "Role", "System", new { id = Html.Encode( role )}, null )%> <%} %> <% } %> <% } else { %> 还未加入任何角色 <% } %>
<%=Html.ActionLink("Back to List", "Index") %> ?

?编辑test123

image image

重设test123密码(实际应用上勿使用默认加密算法)

Add ResetPassword View

ResetPassword

重新产生密码

新密码:<% =Html.Encode(ViewData["newpw"])%>

image image

[C#][ASP.NET MVC]实做成员和角色管理

将test123加入 Normal角色中

image image

这样就完成了成员和角色管理功能了。

贺!一百篇达成

自己从去年8月加入点博客后,借由写博客文章提升自己,也认识了很多同好

收获说真的还不少,期望自己在往后的日子能继续持续下去,最后,先预祝大家虎年行大运。

原文:大专栏  [C#][ASP.NET MVC]实做成员和角色管理

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号