我已经为我的网页创建了一个自定义属性...在我创建的基页类中,如果设置了该属性,我将尝试拉入。不幸的是,它不会作为GetCustomAttributes函数的一部分返回。仅当我显式地使用typeof(myclass)来创建类时。我有一种感觉,这是由于asp.net类是如何生成的。有没有人对如何让它工作有什么建议?
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 viewable)
{
_permissionSet = permission;
_viewable = viewable;
}
public string PermissionSetRequired
{
get { return _permissionSet; }
}
public bool Viewable
{
get { return _viewable; }
}
}
}
AdminOnly类
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类
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();
}
}
}
}
}
发布于 2010-01-21 02:55:50
您已将AttributeUsage.Inherited成员设置为false。当设置为false时,从您的类继承的类不会继承该属性(这就是页面/控件在ASP.NET中的工作方式)。这就是为什么当您显式地使用typeof(类名)时,会找到该属性。
https://stackoverflow.com/questions/2103947
复制相似问题