2010-01-20 42 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