主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(一)
数据结构
权限分配
1.在项目中新建文件夹Helpers
2.在HR.Helpers文件夹下添加EnumMoudle.Cs
namespace HR.Helpers
{
public enum EnumMoudle
{
/// <summary>
/// 模块
/// </summary>
[EnumTitle("用户管理")]
SysUserManage_Role = ,
[EnumTitle("机构管理")]
Department = , [EnumTitle("人事资料")]
Employees = , [EnumTitle("系统管理")]
BaseInfo = ,
}
}
3.在HR.Helpers文件夹下添加ControllerBase.Cs
namespace HR.Helpers
{
public class ControllerBase : Controller
{
/// <summary>
/// 操作人,传IP....到后端记录
/// </summary>
public virtual Operater Operater
{
get
{
return null;
}
} /// <summary>
/// 分页大小
/// </summary>
public virtual int PageSize
{
get
{
return ;
}
} protected ContentResult JsonP(string callback, object data)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
return this.Content(string.Format("{0}({1})", callback, json));
} /// <summary>
/// 当弹出DIV弹窗时,需要刷新浏览器整个页面
/// </summary>
/// <returns></returns>
public ContentResult RefreshParent(string alert = null)
{
var script = string.Format("<script>{0}; parent.location.reload(1)</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
} public new ContentResult RefreshParentTab(string alert = null)
{
var script = string.Format("<script>{0}; if (window.opener != null) {{ window.opener.location.reload(); window.opener = null;window.open('', '_self', ''); window.close()}} else {{parent.location.reload(1)}}</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
} /// <summary>
/// 用JS关闭弹窗
/// </summary>
/// <returns></returns>
public ContentResult CloseThickbox()
{
return this.Content("<script>top.tb_remove()</script>");
} /// <summary>
/// 警告并且历史返回
/// </summary>
/// <param name="notice"></param>
/// <returns></returns>
public ContentResult Back(string notice)
{
var content = new StringBuilder("<script>");
if (!string.IsNullOrEmpty(notice))
content.AppendFormat("alert('{0}');", notice);
content.Append("history.go(-1)</script>");
return this.Content(content.ToString());
} public ContentResult PageReturn(string msg, string url = null)
{
var content = new StringBuilder("<script type='text/javascript'>");
if (!string.IsNullOrEmpty(msg))
content.AppendFormat("alert('{0}');", msg);
if (string.IsNullOrWhiteSpace(url))
url = Request.Url.ToString();
content.Append("window.location.href='" + url + "'</script>");
return this.Content(content.ToString());
} /// <summary>
/// 转向到一个提示页面,然后自动返回指定的页面
/// </summary>
/// <param name="notice"></param>
/// <param name="redirect"></param>
/// <returns></returns>
public ContentResult Stop(string notice, string redirect, bool isAlert = false)
{
var content = "<meta http-equiv='refresh' content='1;url=" + redirect + "' /><body style='margin-top:0px;color:red;font-size:24px;'>" + notice + "</body>"; if (isAlert)
content = string.Format("<script>alert('{0}'); window.location.href='{1}'</script>", notice, redirect); return this.Content(content);
} /// <summary>
/// 在方法执行前更新操作人
/// </summary>
/// <param name="filterContext"></param>
public virtual void UpdateOperater(ActionExecutingContext filterContext)
{
if (this.Operater == null)
return; WCFContext.Current.Operater = this.Operater;
} public virtual void ClearOperater()
{
//TODO
} /// <summary>
/// AOP拦截,在Action执行后
/// </summary>
/// <param name="filterContext">filter context</param>
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
RenderViewData(); this.ClearOperater();
} protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
this.UpdateOperater(filterContext);
base.OnActionExecuting(filterContext); //在方法执行前,附加上PageSize值
filterContext.ActionParameters.Values.Where(v => v is Request).ToList().ForEach(v => ((Request)v).PageSize = this.PageSize);
} /// <summary>
/// 产生一些视图数据
/// </summary>
protected virtual void RenderViewData()
{
} /// <summary>
/// 当前Http上下文信息,用于写Log或其他作用
/// </summary>
public WebExceptionContext WebExceptionContext
{
get
{
var exceptionContext = new WebExceptionContext
{
IP = Fetch.UserIp,
CurrentUrl = Fetch.CurrentUrl,
RefUrl = (Request == null || Request.UrlReferrer == null) ? string.Empty : Request.UrlReferrer.AbsoluteUri,
IsAjaxRequest = (Request == null) ? false : Request.IsAjaxRequest(),
FormData = (Request == null) ? null : Request.Form,
QueryData = (Request == null) ? null : Request.QueryString,
RouteData = (Request == null || Request.RequestContext == null || Request.RequestContext.RouteData == null) ? null : Request.RequestContext.RouteData.Values
}; return exceptionContext;
}
} /// <summary>
/// 发生异常写Log
/// </summary>
/// <param name="filterContext"></param>
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
var e = filterContext.Exception; LogException(e, this.WebExceptionContext);
} protected virtual void LogException(Exception exception, WebExceptionContext exceptionContext = null)
{
//do nothing!
}
} public class WebExceptionContext
{
public string IP { get; set; }
public string CurrentUrl { get; set; }
public string RefUrl { get; set; }
public bool IsAjaxRequest { get; set; }
public NameValueCollection FormData { get; set; }
public NameValueCollection QueryData { get; set; }
public RouteValueDictionary RouteData { get; set; }
}
}
4.在项目文件夹中新建ControllerBase.cs
namespace HR
{
public abstract class ControllerBase:HR.Helpers.ControllerBase
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
} protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
}
5.在项目中新建RoleControllerBase.cs
namespace HR
{
public class RoleControllerBase : ControllerBase
{
SystemUserRepository sysuserrepository = new SystemUserRepository();
/// <summary>
/// 用户权限
/// </summary>
public virtual List<EnumMoudle> PermissionList
{
get
{
var permissionList = new List<EnumMoudle>();
return permissionList;
}
}
public string BusinessPermissionString { get; set; }
[NotMapped]
public List<EnumMoudle> BusinessPermissionList
{
get
{
if (string.IsNullOrEmpty(BusinessPermissionString))
return new List<EnumMoudle>();
else
return BusinessPermissionString.Split(",".ToCharArray()).Select(p => int.Parse(p)).Cast<EnumMoudle>().ToList();
}
set
{
BusinessPermissionString = string.Join(",", value.Select(p => (int)p));
}
}
/// <summary>
/// Action方法执行前没有权限提示信息
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
if (noAuthorizeAttributes.Length > )
return; base.OnActionExecuting(filterContext); bool hasPermission = true;
var permissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();
permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>().Union(permissionAttributes);
var attributes = permissionAttributes as IList<PermissionAttribute> ?? permissionAttributes.ToList();
if (permissionAttributes != null && attributes.Count() > )
{
string cookie = CookieHelper.GetValue("SystemUserID");
if (string.IsNullOrEmpty(cookie))
{
filterContext.Result = Content("您没有登录!");
}
else
{
int mid = int.Parse(CookieHelper.GetValue("SystemUserID"));
var model = sysuserrepository.GetModel(mid);
BusinessPermissionString = model.BusinessPermissionString;
hasPermission = true;
foreach (var attr in attributes)
{
foreach (var permission in attr.Permissions)
{
if (!BusinessPermissionList.Contains(permission))
{
hasPermission = false;
break;
}
}
} if (!hasPermission)
{
if (Request.UrlReferrer != null)
filterContext.Result = this.Stop("您没有权限!", "/default/ng");
else
filterContext.Result = Content("您没有权限!");
}
}
}
}
}
}
6.在每个Controller继承RoleControllerBase类
public class EmployeesController : RoleControllerBase
7.在HR.Helpers文件夹下添加PermissionAttribute.Cs ,并继承 FilterAttribute, IActionFilter
namespace HR.Helpers
{
public class PermissionAttribute : FilterAttribute, IActionFilter
{
public List<EnumMoudle> Permissions { get; set; } public PermissionAttribute(params EnumMoudle[] parameters)
{
Permissions = parameters.ToList();
} public void OnActionExecuted(ActionExecutedContext filterContext)
{
//throw new NotImplementedException();
} public void OnActionExecuting(ActionExecutingContext filterContext)
{
//throw new NotImplementedException();
}
}
}
8.然后在Controller或者Action方法加上验证
[Permission(EnumMoudle.Employees),Authorize, ValidateInput(false)]
[Permission(EnumMoudle.SysUserManage_Role)]
9.在用户管理Controller中添加权限分配,修改方法
#region 添加管理员
/// <summary>
/// 添加页
/// </summary>
/// <param name="model">管理员实体类</param>
/// <returns></returns>
[Authorize]
public ActionResult Add()
{
var moudleList = EnumHelper.GetItemValueList<EnumMoudle>();
this.ViewBag.MoudleList = new SelectList(mouldeList, "Key", "Value"); return View();
} /// <summary>
/// 添加事件
/// </summary>
/// <param name="model">实体类</param>
/// <param name="fc"></param>
/// <returns></returns>
[Authorize, HttpPost, ValidateInput(false)]
public ActionResult Add(SystemUser model, FormCollection fc)
{
model.BusinessPermissionString = fc["MoudelList"];
model.State = ;
model.CreateTime = DateTime.Now;
systemuserrepository.SaveOrEditModel(model);
return RedirectToAction("UserList");
}
#endregion //修改权限
[Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Edit(int id, FormCollection fc)
{
var model = systemuserrepository.GetModel(id); if (model != null)
{
string password = model.PassWord;
if (Request.Form["PassWord"] != "")
{
model.BusinessPermissionString = fc["MoudleList"];
UpdateModel(model);
systemuserrepository.SaveOrEditModel(model);
}
else
{
model.BusinessPermissionString = fc["MoudleList"];
UpdateModel(model);
model.PassWord = password;
systemuserrepository.SaveOrEditModel(model);
}
return RedirectToAction("userlist");
}
else
return View("");
}
#endregion
[Authorize]
public ActionResult Edit(int id)
{
var model = systemuserrepository.GetModel(id);
if (model != null)
{
var moudleList = EnumHelper.GetItemValueList<EnumBusinessPermission>();
this.ViewBag.MoudleList = new SelectList(moudleList, "Key", "Value", string.Join(",", model.BusinessPermissionString.ToString())); return View(model);
}
else
return View("");
}
关于EnumHelper枚举帮助类代码
点击获取页面
声明:本博客高度重视知识产权保护,发现本博客发布的信息包含有侵犯其著作权的链接内容时,请联系我,我将第一时间做相应处理,联系邮箱ffgign@qq.com。
作者:Mark Fan (小念头) 来源:http://cube.cnblogs.com
说明:未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如有疑问,可以通过 ffgign@qq.com 联系作者,本文章采用 知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可
Moudle
主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(一)的更多相关文章
- 主攻ASP.NET.4.5.1 MVC5.0之重生:系统角色与权限(二)
系统角色篇 数据结构 用户管理 Controller代码 public class SystemUserController : Controller { //public void Log() // ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:空地搭建一个包含 Ninject框架 项目
1.创建一个空白解决方案 2.添加一个类库 名称为XXX.Domain 3.添加一个ASP.MVC 名称为XXX.WebUI 4.选着空模版,勾选MVC核心引用 5.添加单元测试项目XXX.UntiT ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:政府行政网站常用友情链接跳转javascript[干货分享]
<!-----------------------------------> <script language="JavaScript" type="t ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:在项目中使用zTree jQuery 树插件
效果图和json格式 Controllers代码 using HR.Models; using HR.Models.Repository; /***************************** ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:创建UIHelper通用自定义分页和选择开关与PagesHelper和IsSelect简单用法
@helper放入地方 分页效果 选择开关编辑调用 <dl> <dd class="dc1">是否主管:</dd> <dd> @UI ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页
路径访问的几种方式和分页效果 显示其它类别的效果和多数据分页效果 默认访问网站路径效果和多数据分页效果 URL路径访问可页面 http://localhost:5339/stationery http ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:Web项目语音朗读网页文本,简单语音提示浏览状态
第一步 添加SpeechLib.dll 下载SpeechLib.dll: 在项目中并且引用DLL using SpeechLib; using System.Threading; 第二步 调用并使用 ...
- 主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP
原文:主攻ASP.NET MVC4.0之重生:ASP.NET MVC使用JSONP 原文地址 http://www.codeguru.com/csharp/.net/net_asp/using-jso ...
- IoC实践--用Autofac实现MVC5.0的IoC控制反转方法
Autofac是一个.net平台下发性能还不错的IoC框架,利用它可以实现依赖注入和控制反转,使自己的软件模块之间的耦合性大大降低,让软件扩展.维护更加容易.控制反转(Inversion of Con ...
随机推荐
- 安装webpack最新版本出现错误
安装完了webpack出现了以下错误 解决办法 cnpm install webpack-cli -D 安装之后,就可以正常使用webpack了
- valgrind调查内存leak
快有几个月没更新了,记录一下最近解决问题用到的工具吧. 最近代码跑压力测试,总是发现内存在无规律的慢慢增加,因此在Android上用上了大名顶顶的valgrind,说实话,真是名不虚传, 真是建议以后 ...
- JavaBean属性
一个JavaBean对象的属性应该是可访问的.这个属性可以是任意合法的Java数据类型,包括自定义Java类. 一个JavaBean对象的属性可以是可读写,或只读,或只写.JavaBean对象的属性通 ...
- java后台如何根据表单中input的顺序获取value值
如果java后台准备用Servlet来实现,可以直接在doPost( )或者doGet( )中使用如下语句:request.setCharacterEndoding("UTF-8" ...
- 内存空间申请(C)
标准C,C++: malloc----free new----delete WINDOWS API: gnew(.net) LocalAlloc----LocalFree GlobalAlloc--- ...
- Android开发:《Gradle Recipes for Android》阅读笔记(翻译)2.2——将Eclipse开发的项目导入到AndroidStudio
问题: 你想要将一个Eclipse ADT项目导入到Android Studio中. 解决方案: Android Studio提供了一个导入向导,可以重写已有的项目. 详细: 在Android Stu ...
- HTML学习笔记——语法+骨架
一.什么是HTML HTML是用来制作网页的标记语言 HTML是Hypertext Markup Language的英文缩写,即超文本标记语言 HTML语言是一种标记语言,不需要编译,直接由浏览器执行 ...
- 【BZOJ3029】守卫者的挑战 概率+背包
[BZOJ3029]守卫者的挑战 Description 打开了黑魔法师Vani的大门,队员们在迷宫般的路上漫无目的地搜寻着关押applepi的监狱的所在地.突然,眼前一道亮光闪过.“我,Nizem, ...
- Dictionary——通过value找Key
Dictionary<string, string> dic = GetRoleDescriptions(); string key = dic.FirstOrDefault(x => ...
- 根据字段表 自动创建 表SQL
create PROC CreateTableSql ) AS ) ,) ,) ) ,) ,) ,@IsIdentity bit ,@IsNull bit ,@IsPrimaryKey bit ),) ...