Can you evaluate an attribute on a method at runtime?
I have a Winforms project that is loosely based on MVVM. Security is implemented by the domain layer by using the PrincipalPermissionAttribute, like so:
Public Class Order
<PrincipalPermissionAttribute(SecurityAction.Demand, Role:="Managers")> _
Public Sub ChangeBillingAddress(NewAddress as Address)
Me.BillingAddress = NewAddress
End Sub
End Class
I would l开发者_JAVA百科ike for my ViewModel to be able to instruct the view on which controls to enable/disable based on the PrincipalPermissionAttribute in the domain:
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
Is there a way for the ViewModel to evaluate the PrincipalPermissionAttribute and determine if the current Thread.Principal will succeed?
Yes, you most definitely can get back the attributes on the method and do stuff with them.
For example (sorry in C#):
return _Order.GetType()
.GetMethod("ChangeBillingAddress")
.GetCustomAttributes(typeof(PrincipalPermissionAttribute), true)
.Cast<PrincipalPermissionAttribute>()
.All(r => IsPermittedAccess(r, Thread.CurrentPrincipal));
Where you can work out what to do with the attribute:
bool IsPermittedAccess(PrincipalPermissionAttribute rule, IPrincipal user)
{
// return ?
throw new NotImplementedException();
}
I'll leave the last task of deciding whether the user meets the attribute's requirements or not. I'm not familiar enough with that part of the framework. Also you can deal with the error handling (e.g. method doesn't exist with that name).
I'll also add that you would probably want to cache (in a static field perhaps?) the results of the reflection on the method since it'll never change. You'll also want to be sure that your view model is firing property change notifications when the principal changes or principal's roles collection changes (that is, if it does in deed change).
精彩评论