在Mvc中使用自定义属性进行权限判断
下面的代码参考了 AuthorizeAttribute , 实际中 if (!AuthorizeCore()) {。。。。。} 的代码根据实际情况进行改写,如自动跳转至登录,或我现在在DWZ中可以返回 JSON格式的数据等。
这样,至少可以做的是少写没必要的很多重复的代码了。
少写几行代码比什么都重要。
/// <summary> /// 自定权限操作的方法 , added by zbw911 /// <example> [AllowPurviews] 至少要求登录</example> /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class AllowPurviewsAttribute : ActionFilterAttribute { private string _purviews; private string[] _purviewsSplit = new string[0]; public string Purviews { get { return _purviews; } set { _purviews = value; _purviewsSplit = SplitString(_purviews); } } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (OutputCacheAttribute.IsChildActionCacheActive(filterContext)) { throw new InvalidOperationException("在缓存状态下无法使用此特性"); } var descriptor = filterContext.ActionDescriptor; bool allowAnonymous; if (!descriptor.IsDefined(typeof(AllowAnonymousAttribute), true)) { ControllerDescriptor controllerDescriptor = filterContext.ActionDescriptor.ControllerDescriptor; allowAnonymous = controllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true); } else { allowAnonymous = true; } if (allowAnonymous) { return; } if (!AuthorizeCore()) { var json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; json.Data = "nono"; filterContext.Result = json; } } private bool AuthorizeCore() { if (SessionAll.AdminInfo == null) return false; return SessionAll.AdminInfo.PurviewsKeys.Any(x => this._purviewsSplit.Contains(x)); } internal static string[] SplitString(string original) { if (string.IsNullOrEmpty(original)) { return new string[0]; } IEnumerable<string> source = from piece in original.Split(new char[] { ',' }) let trimmed = piece.Trim() where !string.IsNullOrEmpty(trimmed) select trimmed; return source.ToArray<string>(); } }