2010-01-20 123 views
1

我为我的网页创建了一个自定义属性...在创建的基本页面类中,我试图拉如果该属性已设置。不幸的是,它不会作为GetCustomAttributes函数的一部分回来。只有当我明确使用typeof(myclass)来创建类。我有一种感觉,这是由于如何生成asp.net类。任何人有任何建议如何让这个工作?检索网页上的自定义属性类(.net)

命名空间SecuritySample.SecurityCode { [AttributeUsage(AttributeTargets.All,继承=假,=的AllowMultiple真)] 公共密封类MHCSecurityAttribute:属性 { 私人字符串_permissionSet; private bool _viewable;

public MHCSecurityAttribute(string permission, bool viewable) 
    { 
     _permissionSet = permission; 
     _viewable = viewable; 
    } 

    public string PermissionSetRequired 
    { 
     get { return _permissionSet; } 
    } 

    public bool Viewable 
    { 
     get { return _viewable; } 
    } 
} 

}

使用系统; using SecuritySample.SecurityCode;

命名空间SecuritySample { [MHCSecurityAttribute( “testpermission”,假)] 公共部分类AdminOnlyPage:BasePage的,IMHCSecurityControl { 保护无效的Page_Load(对象发件人,EventArgs的) {

} 

    public void DisableControl() 
    { 
     Server.Transfer("Error.aspx"); 
    } 

    public void EnableControl() 
    { 
    } 
} 

}

using System.Web.UI.WebControls;

命名空间SecuritySample.SecurityCode { 公共类的BasePage:页 { 私人字符串_user;

protected override void OnLoadComplete(EventArgs e) 
    { 
     base.OnLoadComplete(e); 

     _user = string.Empty; 
     if (Session.Contents["loggedInUser"] != null) 
      _user = Session["loggedInUser"].ToString(); 

     // perform security check 

     // check page level 
     if (this is IMHCSecurityControl) 
     { 
      System.Reflection.MemberInfo info = this.GetType(); 
      object[] attributes = info.GetCustomAttributes(false); 
      bool authorized = false; 

      if ((attributes != null) && (attributes.Length > 0)) 
      { 
       foreach(MHCSecurityAttribute a in attributes) 
       { 
        if ((MHCSecurityCheck.IsAuthorized(_user, a.PermissionSetRequired))) 
        { 
         ((IMHCSecurityControl) this).EnableControl(); 
         authorized = true; 
         break; 
        } 
       } 

       if (!authorized) 
        ((IMHCSecurityControl)this).DisableControl(); 
      } 
     } 
    } 
} 

}

回答

1

您已设置AttributeUsage .Inherited成员为false。当设置为false时,该属性不会被继承自类的类继承(这是Pages/Controls在ASP.NET中的工作方式)。这就是为什么当你显式使用typeof(你的类名)时,找到属性。

+0

其实你的意思是将它设置为true ...如果我将它设置为true并且执行GetCustomAttributes(true)...我可以看到该类。 – user38734 2010-01-20 19:04:13