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

依然范特西╮ 提交于 2019-12-10 23:55:38

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/21925245/how-to-pass-method-parameter-into-methods-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!