今天在做权限开发的时候,在控制器的方法上添加了一些特性,希望在过滤器中获取到这些特性,查找了一些资料,终于找到了办法:
var action = context.ActionDescriptor as ControllerActionDescriptor; var permission = action.MethodInfo.GetCustomAttribute<PermissionAttribute>();
具体的实现代码如下:
/// <summary> /// 国际差旅住宿标准的保存 /// </summary> /// <returns></returns> [AuthorityTypeCodeAttribute("B000051", HtmlReturnResultType.JSON)] public ActionResult InternationalHotelSave()
/// <summary> /// 页面请求返回的字符串类型 /// </summary> public enum HtmlReturnResultType { JSON = 0, HTML = 1 } /// <summary> /// 页面菜单中权限标识的特性,设置控制器中的方法的权限标识符 /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] public class AuthorityTypeCodeAttribute : Attribute { /// <summary> /// 页面的权限标识,也就是 页面标签 的编码,例如: B000051 ,在页面菜单权限中设置 /// </summary> public string AuthorityCode { get; set; } /// <summary> /// 返回的结果类型 /// </summary> public HtmlReturnResultType ReturnResultType { get; set; } /// <summary> /// 页面菜单中权限标识的特性 /// </summary> /// <param name="_AuthorityCode"></param> /// <param name="htmlReturnResult">页面请求返回的字符串类型</param> public AuthorityTypeCodeAttribute(string _AuthorityCode, HtmlReturnResultType htmlReturnResult) { this.AuthorityCode= _AuthorityCode; this.ReturnResultType = htmlReturnResult; } }
只摘取过滤器中的部分代码:
public class GDCActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { string lk = GDCUtility.GetParamNoSpace("lk"); UserInfoModel um = GDCObjectInfosBLL.CurrentUserBLL.GetLoginInfo(lk); #region 判断权限 var action = context.ActionDescriptor as ControllerActionDescriptor; var permission = action.MethodInfo.GetCustomAttribute<AuthorityTypeCodeAttribute>(); if (permission != null) { string authorityCode = permission.AuthorityCode; HtmlReturnResultType htmlReturnResultType = permission.ReturnResultType; bool userMenuButtonAuthority = GDCObjectInfosBLL.CurrentAuthorityBLL.UserMenuButtonAuthority(um, authorityCode); if (!userMenuButtonAuthority) { ResultInfoModel rim = new ResultInfoModel("02", "未授权,非法请求!"); if (htmlReturnResultType == HtmlReturnResultType.HTML) { context.Result = GDCHttpContext.GDCGetViewResultError(rim);// result; } else if(htmlReturnResultType == HtmlReturnResultType.JSON) { context.Result = new Microsoft.AspNetCore.Mvc.JsonResult(rim); } return; } } #endregion
标签:core,asp,HtmlReturnResultType,Attribute,context,action,权限,public,页面 From: https://www.cnblogs.com/huaan011/p/18416293