In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the method tutorial of setting system roles and permissions by ASP.NET.4.5.1+MVC5.0". In the daily operation, I believe that many people have doubts about the method tutorial of setting system roles and permissions by ASP.NET.4.5.1+MVC5.0. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the "ASP.NET.4.5.1+MVC5.0 tutorial on how to set up system roles and permissions". Next, please follow the editor to study!
Data structure
Authority assignment
1. Create a new folder Helpers in the project
two。 Add EnumMoudle.Cs under the HR.Helpers folder
The copy code is as follows:
Namespace HR.Helpers
{
Public enum EnumMoudle
{
/ / /
/ / module
/ / /
[EnumTitle ("user Management")]
SysUserManage_Role = 102
[EnumTitle ("organizational Management")]
Department = 201
[EnumTitle (personnel Information)]
Employees = 301
[EnumTitle ("system Management")]
BaseInfo = 404
}
}
3. Add ControllerBase.Cs under the HR.Helpers folder
The copy code is as follows:
Namespace HR.Helpers
{
Public class ControllerBase: Controller
{
/ / /
/ / operator, pass IP.... Record to backend
/ / /
Public virtual Operater Operater
{
Get
{
Return null
}
}
/ / /
/ / Page size
/ / /
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))
}
/ / /
/ / when the DIV pop-up window pops up, the entire browser page needs to be refreshed.
/ / /
/ / /
Public ContentResult RefreshParent (string alert = null)
{
Var script = string.Format ("{0}; parent.location.reload (1)", string.IsNullOrEmpty (alert)? String.Empty: "alert ('" + alert + "'))
Return this.Content (script)
}
Public new ContentResult RefreshParentTab (string alert = null)
{
Var script = string.Format ("{0}; if (window.opener! = null) {{window.opener.location.reload (); window.opener = null;window.open ('','_ self','); window.close ()}} else {{parent.location.reload (1)}}", string.IsNullOrEmpty (alert)? String.Empty: "alert ('" + alert + "'))
Return this.Content (script)
}
/ / /
/ / close the pop-up window with JS
/ / /
/ / /
Public ContentResult CloseThickbox ()
{
Return this.Content ("top.tb_remove ()")
}
/ / /
/ / warning and history is returned
/ / /
/ / /
/ / /
Public ContentResult Back (string notice)
{
Var content = new StringBuilder ("")
If (! string.IsNullOrEmpty (notice))
Content.AppendFormat ("alert ('{0}');", notice)
Content.Append ("history.go (- 1)")
Return this.Content (content.ToString ())
}
Public ContentResult PageReturn (string msg, string url = null)
{
Var content = new StringBuilder ("")
If (! string.IsNullOrEmpty (msg))
Content.AppendFormat ("alert ('{0}');", msg)
If (string.IsNullOrWhiteSpace (url))
Url = Request.Url.ToString ()
Content.Append ("_ window.location.href='" + url + "'")
Return this.Content (content.ToString ())
}
/ / /
/ / go to a prompt page and automatically return to the specified page
/ / /
/ / /
/ / /
/ / /
Public ContentResult Stop (string notice, string redirect, bool isAlert = false)
{
Var content = "" + notice + ""
If (isAlert)
Content = string.Format ("alert ('{0}'); _ window.location.href=' {1}'", notice, redirect)
Return this.Content (content)
}
/ / /
/ / update the operator before the method is executed
/ / /
/ / /
Public virtual void UpdateOperater (ActionExecutingContext filterContext)
{
If (this.Operater = = null)
Return
WCFContext.Current.Operater = this.Operater
}
Public virtual void ClearOperater ()
{
/ / TODO
}
/ / /
/ AOP interception, after Action execution
/ / /
/ filter context
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)
/ / append the PageSize value before the method execution
FilterContext.ActionParameters.Values.Where (v = > v is Request). ToList (). ForEach (v = > (Request) v). PageSize = this.PageSize)
}
/ / /
/ / generate some view data
/ / /
Protected virtual void RenderViewData ()
{
}
/ / /
/ / current Http context information, used to write Log or other functions
/ / /
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
}
}
/ / /
/ / write Log when an exception occurs
/ / /
/ / /
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. Create a new ControllerBase.cs in the project folder
The copy code is as follows:
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. Create a new RoleControllerBase.cs in the project
The copy code is as follows:
Namespace HR
{
Public class RoleControllerBase: ControllerBase
{
SystemUserRepository sysuserrepository = new SystemUserRepository ()
/ / /
/ / user permissions
/ / /
Public virtual List PermissionList
{
Get
{
Var permissionList = new List ()
Return permissionList
}
}
Public string BusinessPermissionString {get; set;}
[NotMapped]
Public List BusinessPermissionList
{
Get
{
If (string.IsNullOrEmpty (BusinessPermissionString))
Return new List ()
Else
Return BusinessPermissionString.Split ("," .ToCharArray ()) .Select (p = > int.Parse (p)) .Cast () .ToList ()
}
Set
{
BusinessPermissionString = string.Join (",", value.Select (p = > (int) p))
}
}
/ / /
/ / there is no permission prompt before the Action method is executed
/ / /
/ / /
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 ()
PermissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes (typeof (PermissionAttribute), false). Cast (). Union (permissionAttributes)
Var attributes = permissionAttributes as IList? PermissionAttributes.ToList ()
If (permissionAttributes! = null & & attributes.Count () > 0)
{
String cookie = CookieHelper.GetValue ("SystemUserID")
If (string.IsNullOrEmpty (cookie))
{
FilterContext.Result = Content ("you are not logged in!")
}
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 ("you don't have permission!" , "/ default/ng")
Else
FilterContext.Result = Content ("you don't have permission!")
}
}
}
}
}
}
6. Inherit the RoleControllerBase class in each Controller
Public class EmployeesController: RoleControllerBase
7. Add PermissionAttribute.Cs under the HR.Helpers folder, and inherit FilterAttribute, IActionFilter
The copy code is as follows:
Namespace HR.Helpers
{
Public class PermissionAttribute: FilterAttribute, IActionFilter
{
Public List 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. Then add validation to the Controller or Action method
The copy code is as follows:
[Permission (EnumMoudle.Employees), Authorize, ValidateInput (false)]
[Permission (EnumMoudle.SysUserManage_Role)]
9. Add permission assignment and modify method in user management Controller
The copy code is as follows:
# add administrator to region
/ / /
/ / add Page
/ / /
/ / Administrator entity class
/ / /
[Authorize]
Public ActionResult Add ()
{
Var moudleList = EnumHelper.GetItemValueList ()
This.ViewBag.MoudleList = new SelectList (mouldeList, "Key", "Value")
Return View ()
}
/ / /
/ / add event
/ / /
/ / entity class
/ / /
/ / /
[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
/ / modify permissions
[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
The copy code is as follows:
[Authorize]
Public ActionResult Edit (int id)
{
Var model = systemuserrepository.GetModel (id)
If (model! = null)
{
Var moudleList = EnumHelper.GetItemValueList ()
This.ViewBag.MoudleList = new SelectList (moudleList, "Key", "Value", string.Join (",", model.BusinessPermissionString.ToString ())
Return View (model)
}
Else
Return View ("404")
}
At this point, the study on the "ASP.NET.4.5.1+MVC5.0 setting system roles and permissions method tutorial" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.