如何将自定义CodeAccessSecurityAttribute应用于属性?

时间:2015-08-14 00:17:53

标签: c# custom-attributes

我正在尝试实施自定义CodeAccessSecurityAttribute,如下所示:

[AttributeUsage(AttributeTargets.Property)]
public class AuthoriseAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
{
    // custom security implementation
}

我想限制对属性的访问,例如:

public class Dashboard : Page
{
    [Authorise(SecurityAction.Demand)]
    public List<RedirectNameValueBo> ClientsContractExpiring
    {
        set
        {
            this.ctlClientContractExpiry.ItemList = value;
            this.ctlClientContractExpiry.Visible = true;
        }
    }
}

但是我收到了错误:

Error emitting 'Namespace.AuthoriseAttribute' attribute -- 'Security custom attribute attached to invalid parent.'

对于记录,如果我将AttributeUsage更改为AttributeTargets.Method,并将该属性应用于方法,则可以正常工作,例如:

[AttributeUsage(AttributeTargets.Method)]
public class AuthoriseAttribute : System.Security.Permissions.CodeAccessSecurityAttribute
{
    // custom security implementation
}

[Authorise(SecurityAction.Demand)]
protected void Page_Load(object sender, EventArgs e)
{

}

我需要做些什么才能将此自定义属性应用于属性?

1 个答案:

答案 0 :(得分:0)

我也碰到了这个问题。不幸的是CodeAccessSecurityAttribute和从它派生的所有东西都不能应用于属性。但是有一个简单的解决方法:将该属性应用于getter和/或所需属性的setter - getter和setter是引擎盖下的方法。我在Visual Basic .NET中给你举例,你应该能够将它翻译成C#。

'This does not work:
<PrincipalPermission(SecurityAction.Demand, Role:="Administrator")>
Public Property IsEnabled As Boolean

'This works:
Private _isEnabled As Boolean
Public Property IsEnabled As Boolean
  <PrincipalPermission(SecurityAction.Demand, Role:="Administrator")>
  Get
    Return _isEnabled
  End Get
  <PrincipalPermission(SecurityAction.Demand, Role:="Administrator")>
  Set (value As Boolean)
    _isEnabled = value
  End Set
End Property