ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统相关的知识,希望对你有一定的参考价值。
今天将使用Simplemembership进行权限控制
我们使用mvc的AuthorizeAttribute来实现对Controller and Action权限控制
看如下标为红色的代码片段:
/// <summary> /// 删除数据操作 /// </summary> /// <param name="id"></param> /// <returns></returns> [MVCSystemAuthorizeAttribute(permission = "删除")] [HttpPost] public JsonResult ArticlesDelete(int id) { if (id > 0) { var aList = db.DB_Articles.Find(id); db.DB_Articles.Remove(aList); db.SaveChanges(); return Json(1, JsonRequestBehavior.AllowGet); } else { return Json(0, JsonRequestBehavior.AllowGet); } } /// <summary> /// 添加修改 /// </summary> /// <param name="id"></param> /// <returns></returns> [MVCSystemAuthorizeAttribute(permission = "添加")] public ActionResult ArticleAddEdit(int id) { ViewBag.Type = db.DB_ArticleTypes.ToList(); ViewBag.Member = db.DB_Members.ToList(); if (id == 0) { var aList = new M_Articles(); return View(aList); } else { var aList = db.DB_Articles.Find(id); return View(aList); } }
从之前生成的表可以看出,Permission表存储各个Action的名字(例如一个一个controller中的曾删改查各个Action),PermissionsInRoles表就是存储权限和角色关系。
然后我们在Filters/InitializeSimpleMembershipAttribute.cs中建立一个自己的MVCSystemAuthorizeAttribute继承AuthorizeAttribute,并重写AuthorizeCore和HandleUnauthorizedRequest方法。
using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Threading; using System.Web.Mvc; using WebMatrix.WebData; using MVCSystem.Web.Models; using MVCSystem.Web.Common; using System.Web; namespace MVCSystem.Web.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute { private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(ActionExecutingContext filterContext) { // 确保每次启动应用程序时只初始化一次 ASP.NET Simple Membership LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } private class SimpleMembershipInitializer { public SimpleMembershipInitializer() { Database.SetInitializer<MVCSystemContext>(null); try { using (var context = new MVCSystemContext()) { if (!context.Database.Exists()) { // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库 // ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true); } catch (Exception ex) { throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex); } } } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class MVCSystemAuthorizeAttribute : AuthorizeAttribute { private bool _authorize; private bool _isPermissionFail = false; public string permission { get; set; } public MVCSystemAuthorizeAttribute() { if (HttpContext.Current.User.Identity.Name != "") { _authorize = true; } else { _authorize = false; } } public MVCSystemAuthorizeAttribute(string permission) { if (HttpContext.Current.User.Identity.Name != "") { _authorize = PermissionManager.CheckUserHasPermision(HttpContext.Current.User.Identity.Name, permission); if (_authorize == false) { _isPermissionFail = true; } } else { _authorize = false; } //_authorize = true; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("HttpContext"); } if (!httpContext.User.Identity.IsAuthenticated) { return false; } else { _authorize = PermissionManager.CheckUserHasPermision(HttpContext.Current.User.Identity.Name, permission); if (_authorize == false) { _isPermissionFail = true; return false; } return true; } // return false; } //protected override bool AuthorizeCore(HttpContextBase httpContext) //{ // return _authorize; //} public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (_isPermissionFail) { filterContext.HttpContext.Response.Redirect("/Admin/Error/ErrorNoper"); } else { base.HandleUnauthorizedRequest(filterContext); } } } }
MVCSystemAuthorizeAttribute(string permission)接受一个permission字符串,这个就是Permission表中的数据,对应的每个Action【增删查改】等名称。
在这个构造参数里判断当前用户是否具有permission这个权限。PermissionManager.CheckUserHasPermision(HttpContext.Current.User.Identity.Name, permission),如果有赋值true给_authorize,表示当前用户有权限访问这个Action。如果没有赋值false给_authorize。
然后我们在common中创建一个类PermissionManager.cs,用来获取登录用户的角色权限:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using MVCSystem.Web.Models; namespace MVCSystem.Web.Common { public class PermissionManager { public static bool CheckUserHasPermision(string userName, string permissionName) { using (MVCSystemContext db = new MVCSystemContext()) { var userId = db.DB_UserProfiles.Single(u => u.UserName == userName).UserId; var roleIdList =db.DB_UsersInRoles.Where(k=>k.UserId==userId).ToList(); foreach (var roles in roleIdList) { var permissionList = (from m in db.DB_PermissionsInRoles where m.RoleId == roles.RoleId join n in db.DB_Permission on m.PermissionId equals n.PermissionId into pp from p in pp.DefaultIfEmpty() select new { PermissionName = (p.PermissionName == null) ? "" : p.PermissionName }).ToList(); foreach (var permission in permissionList) { if (permission.PermissionName == permissionName) { return true; } } } } return false; } } }
这里需要注意的是var roleIdList =db.DB_UsersInRoles.Where(k=>k.UserId==userId).ToList();这句话,ToList()去掉之后会出现数据库已经打开,这里不能打开的错误【已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭】!
然后,我设置当前我登录的账户角色,这里我选择“一般管理员”,而这个角色只有查看数据列表的权限,没有增删改的权限,运行结果如下:
到了这一步,后台搭建的功能基本完成了,接下里主要是完善前台网站的页面,只要有一个漂亮的前端界面,那么接下来的代码工作将会是最简单的了。
作者:boyzi007
出处:http://www.cnblogs.com/boyzi/
QQ:470797533
QQ交流群:364307742
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
以上是关于ASP.NET MVC4.0+EF+LINQ+bui+网站+角色权限管理系统的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET MVC 4、EF 和 LINQ:为多对多关系创建特定的 LINQ 查询