ASP.NET.4.5.1+MVC5.0系统角色和权限讲解

细说ASP.NET.4.5.1+MVC5.0系统角色和权限

MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。

1.在项目中新建文件夹Helpers

2.在HR.Helpers文件夹下添加EnumMoudle.Cs

namespace HR.Helpers

{

public enum EnumMoudle

{

/// <summary>

/// 模块 # codego.net#

/// </summary>

[EnumTitle("用户管理")]

SysUserManage_Role = 102,

[EnumTitle("机构管理")]

Department = 201,

[EnumTitle("人事资料")]

Employees = 301,

[EnumTitle("系统管理")]

BaseInfo = 404,

}

}

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 15;

}

}

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 > 0)

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() > 0)

{

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 = 1;

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("404");

}

#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("404");

}

时间: 2024-10-03 21:20:44

ASP.NET.4.5.1+MVC5.0系统角色和权限讲解的相关文章

主攻ASP.NET.4.5.1 MVC5.0之重生:创建UIHelper通用自定义分页和选择开关与PagesHelper和IsSelect简单用法

@helper放入地方 分页效果 选择开关编辑调用 <dl> <dd class="dc1">是否主管:</dd> <dd> @UIHelper.IsSelect("IsManager",Model.IsManager.ToString()); </dd> </dl> 分页调用 <div class="rg5"> @UIHelper.PagesHelper(Vie

主攻ASP.NET.4.5.1 MVC5.0之重生:在项目中使用zTree jQuery 树插件

效果图和json格式 Controllers代码 using HR.Models; using HR.Models.Repository; /************************************************************************************ * 命名空间:HR.Controllers * Controller: TreeController * 版本号: F 1.0.0.0 * 负责人: Markfan * 电子邮箱:[ema

主攻ASP.NET.4.5.1 MVC5.0之重生:政府行政网站常用友情链接跳转javascript[干货分享]

<!-----------------------------------> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_jumpMenu(targ, selObj, restore) { //v3.0 window.open(selObj.options[selObj.selectedIndex].value); if (restore)

ASP.NET.4.5.1+MVC5.0设置系统角色与权限

Controller代码 public class SystemUserController : Controller { //public void Log() //{ //    string meg = ""; //    int user = int.Parse(CookieHelper.GetValue("SysUserID")); //    string ip = IPHelper.GetUserIp; //    foreach (var item

主攻ASP.NET.4.5.1 MVC5.0之重生:根据产品类别显示菜单分类和分页

路径访问的几种方式和分页效果 显示其它类别的效果和多数据分页效果 默认访问网站路径效果和多数据分页效果 URL路径访问可页面 http://localhost:5339/stationery http://localhost:5339/stationery/Page2 http://localhost:5339/?category=fashion http://localhost:5339/?category=stationery 主要还是看代码和书,写出来的代码 主要使用这个路径显示和分页的效

vivo8.0系统最完美激活xposed框架的教程

对于喜欢钻研手机的伙伴而言,大多时候会玩到xposed框架以及各种功能极强的模块,对于5.0以下的系统版本,只要手机能获得root权限,安装和激活xposed框架是异常轻松的,但随着系统版本的升级,5.0以后的系统,激活xposed框架变得异常艰难,有些教程甚至需要我们刷入Recovery的搞法来激活,这给我们带来非常的难度,特别是对我们新手用户而言,很容易就把手机给刷成砖头. 几个月之前采购了一只vivo8.0系统,网上收集很多资料,捣腾了很久还是不能成功激活Xposed框架,因而一直扔在那里

荣耀8.0系统一键激活XPOSED框架的方法

对于喜欢搞机的小伙伴而言,经常会玩到xposed框架及种类繁多功能极强的模块,对于5.0以下的系统版本,只要手机能获得ROOT权限,安装和激活xposed框架是非常简单的,但随着系统版本的更新,5.0以后的系统,激活xposed框架变得非常艰难,有些教程甚至需要我们刷入recovery的方式来激活,这给我们带来巨大的难度,特别是对我们新手玩家而言,很容易就把手机给刷成木头. 几个星期之前淘了一个荣耀8.0系统,网上找了较多资料,尝试了很久还是不能成功激活XPOSED框架,结果放弃了,一直晾在那里

魅族6.0系统最简单激活Xposed框架的教程

对于喜欢搞机的哥们来说,常常会玩到XPOSED框架及其各类功能强悍的模块,对于5.0以下的系统版本,只要手机能获得root权限,安装和激活XPOSED框架是比较简易的,但随着系统版本的升级,5.0以后的系统,激活XPOSED框架变得比较艰难,有些教程甚至需要我们刷入RECOVERY的做法来激活,这给我们带来极其的难度,特别是对我们新手屌丝来说,很容易就把手机给刷成大砖. 几个星期之前购买了一只魅族6.0系统,网上搜索了非常多教程,捣腾了很久还是没能力成功激活XPOSED框架,因而一直丢在那里没弄

Android 6.0的运行时权限

原文  http://droidyue.com/blog/2016/01/17/understanding-marshmallow-runtime-permission/ 主题 安卓开发 Android 6.0,代号棉花糖,自发布伊始,其主要的特征运行时权限就很受关注.因为这一特征不仅改善了用户对于应用的使用体验,还使得应用开发者在实践开发中需要做出改变. 没有深入了解运行时权限的开发者通常会有很多疑问,比如什么是运行时权限,哪些是运行时的权限,我的应用是不是会在6.0系统上各种崩溃呢,如何才能