Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass method parameter into method's attribute value?

I have a method which is decorated with ClaimsPrincipalPermissionAttribute like this:

[ClaimsPrincipalPermission(SecurityAction.Demand, 
                           Resource = "User", 
                           Operation = "accountId")]
IList<Transaction> ViewTransaction(int accountId)
{
     // some code
}

Is there anyway to pass the accoutId parameter of ViewTransaction to ClaimsPrincipalPermission Operation?

What I want is to use the accountId and then implement custom logic inside ClaimsAuthorizationManager.

like image 755
Vu Nguyen Avatar asked Sep 17 '25 15:09

Vu Nguyen


1 Answers

Attributes expect constant values at compile time. As a result, you cannot pass dynamic values to your attribute and expect it to compile. You would have to resort on some reflection to get this to do what you'd like it to do.

var method = typeof(YourClassType).GetMethod("ViewTransaction");
var attribute = method.GetCustomAttribute(typeof(ClaimsPrincipalPermission)) as ClaimsPrincipalPermission;
attribute.AccountId = 1234;

You would need to expose another property for your attribute, namely AccountId.
There are obviously some concerns around this type of approach and should be weighed heavily before doing this. Make sure that you HAVE to have this type of information passed to your attribute.

Alternatively, if your method lives inside of an MVC controller, you can access the value provider from your filter context as explained in this answer.

ASP MVC C#: Is it possible to pass dynamic values into an attribute?

like image 147
David L Avatar answered Sep 20 '25 05:09

David L