C# 关于Attribute的初级应用

来源:互联网 发布:java redis使用教程 编辑:程序博客网 时间:2024/06/15 07:49

主要是在做关于角色权限验证时用到的

关于后台页面只能被管理员访问,所以单独在每个后台页面的controller上加上对应标签,[Seetting]要放在最前面,即public的前面

然后就是关于Attribute的编写:

namespace System.Web.Mvc
{

//这一行是对这个方法的实例化
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class SettingAttribute : AuthorizeAttribute
    {
        //     初始化 System.Web.Mvc.SettingAttribute 类的新实例。
        //public SettingAttribute();


        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }


            #region 判断是否为管理员
            if (!Common.CheckSettingUser())
            {
                filterContext.Result = new RedirectResult("~/Error/NoPermission");
            }
            #endregion
        }
    }
}