您可以在运行时评估方法的属性吗?

时间:2011-05-17 20:52:00

标签: .net vb.net mvvm attributes

我有一个松散基于MVVM的Winforms项目。安全性由域层使用PrincipalPermissionAttribute实现,如下所示:

Public Class Order

     <PrincipalPermissionAttribute(SecurityAction.Demand, Role:="Managers")> _
    Public Sub ChangeBillingAddress(NewAddress as Address)

        Me.BillingAddress = NewAddress

    End Sub


End Class

我希望我的ViewModel能够根据域中的PrincipalPermissionAttribute指示启用/禁用哪些控件的视图:

Public Class OrderViewModel

    Private _Order as Order
    Public Sub New(Order as Order)
        _Order = Order
    End Sub

    Public Readonly Property ChangeBillingAddressEnabled as Boolean
        Get
            'Here I want to take Thread.CurrentPrincipal and evaluate
            'it's Role against the PrincipalPermissionAttribute on 
            '_Order.ChangeBillingAddress.  If the user will succeed
            'in changing the billing address return True, else return False.
        End Get

    End Property
End Class

ViewModel是否有办法评估PrincipalPermissionAttribute并确定当前的Thread.Principal是否会成功?

1 个答案:

答案 0 :(得分:1)

是的,你绝对可以找回方法的属性并用它们做些事情。

例如(抱歉在C#中):

return _Order.GetType()
             .GetMethod("ChangeBillingAddress")
             .GetCustomAttributes(typeof(PrincipalPermissionAttribute), true)
             .Cast<PrincipalPermissionAttribute>()
             .All(r => IsPermittedAccess(r, Thread.CurrentPrincipal));

您可以在哪里弄清楚如何处理该属性:

bool IsPermittedAccess(PrincipalPermissionAttribute rule, IPrincipal user)
{
    // return ?
    throw new NotImplementedException();
}

我将离开最后一项决定用户是否满足属性要求的任务。我对框架的这一部分不够熟悉。您也可以处理错误处理(例如,该名称不存在方法)。

我还要补充一点,您可能希望缓存(在静态字段中?)方法反射的结果,因为它永远不会改变。您还需要确保您的视图模型在主体更改或主体的角色集合发生更改时触发属性更改通知(即,如果它在契约更改中执行)。

相关问题