如何方法的参数传递到方法的属性值? [英] How to pass method parameter into method's attribute value?

查看:130
本文介绍了如何方法的参数传递到方法的属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个装饰有Cla​​imsPrincipalPermissionAttribute这样的方法:

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
}

反正是有 ViewTransaction 的的 accoutId参数传递给 ClaimsPrincipalPermission操作的?

我要的是使用的帐户ID 的,然后实现内部ClaimsAuthorizationManager定制逻辑。

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

推荐答案

属性期望在编译时间常数的值。其结果是,你不能传递动态值到你的属性,并希望它编译。你将不得不诉诸一些反射来得到这个做你想要它做的事。

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;

您将需要公开为属性,即ACCOUNTID的另一个属性。结果
明明有解决这个类型的方法有些顾虑,应在此之前沉重地压。请确保你必须有这种类型的传递给你的属性信息。

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.

另外,如果你的方法生活的MVC控制器里面,你可以从你的过滤情况下取得的价值提供者在这个答案说明。

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.

<一个href=\"http://stackoverflow.com/questions/2798516/asp-mvc-c-is-it-possible-to-pass-dynamic-values-into-an-attribute\">ASP MVC C#:?是否可以动态值传递到属性

这篇关于如何方法的参数传递到方法的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆