I've create a custom attribute for my web pages... In the base page class I've created I'm trying to pull if that attribute has been set. Unfortunately it does not come back as part of the GetCustomAttributes function. Only if I explicitly use the typeof(myclass) to create the class. I have a feeling it's due to how asp.net classes are generated. Anyone have any suggestions on how to get this to work?
namespace SecuritySample.SecurityCode
{
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public sealed class MHCSecurityAttribute : Attribute
{
private string _permissionSet;
private bool _viewable;
public MHCSecurityAttribute(string permission, bool viewab开发者_开发问答le)
{
_permissionSet = permission;
_viewable = viewable;
}
public string PermissionSetRequired
{
get { return _permissionSet; }
}
public bool Viewable
{
get { return _viewable; }
}
}
}
AdminOnly class
using System;
using SecuritySample.SecurityCode;
namespace SecuritySample
{
[MHCSecurityAttribute("testpermission", false)]
public partial class AdminOnlyPage : BasePage, IMHCSecurityControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void DisableControl()
{
Server.Transfer("Error.aspx");
}
public void EnableControl()
{
}
}
}
BasePage class
using System.Web.UI.WebControls;
namespace SecuritySample.SecurityCode
{
public class BasePage : Page
{
private string _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();
}
}
}
}
}
You have set the AttributeUsage.Inherited member to false. When set to false the attribute is not inherited by classes that inherit from your class (which is how Pages/Controls work in ASP.NET). This is why when you explicitly use typeof(your class name) the attribute is found.
精彩评论