2012-04-18 44 views
0

我正在审核一块,并试图使用一个属性来标记参数应该记录在审计中的方法,以获取更多信息。但是,无论出于何种原因,我似乎无法检查属性是否存在。参数属性没有显示

我的代码:

[Audit(AuditType.GetReport)] 
    public Stream GetReportStream([AuditParameter] Report report) 
    { 
    ... 
    } 

    [AttributeUsage(AttributeTargets.Parameter)] 
    public class AuditParameterAttribute : Attribute 
    { 
    } 

,并在我试图把它拦截器里面:

foreach (ParameterInfo param in invocation.Method.GetParameters()) 
{ 
    var atts = CustomAttributeData.GetCustomAttributes (param); 
    if (param.IsDefined (typeof(AuditParameterAttribute), false)) 
    { 
     attributes.Add (param.Name, invocation.Arguments[param.Position].ToString()); 
    } 
} 

我开始添加一些额外的呼叫,试图让一些工作;这就是为什么额外的var atts在那里。 invocation变量具有有关所调用方法的信息,并且我可以从中获取表示参数的ParameterInfo对象。但是,无论我尝试过什么,我都无法获得任何自定义属性。

我在这里做错了什么?

回答

2

明白了。原来,这是我使用Castle的缺乏经验的问题。我意识到它正在经历一个基于被调用类的接口的代理,它没有我正在寻找的属性。因此,将我的代码更改为:

foreach (ParameterInfo param in invocation.MethodInvocationTarget.GetParameters()) 
{ 
    if (param.IsDefined (typeof(AuditParameterAttribute), false)) 
    { 
     attributes.Add (param.Name, invocation.Arguments[param.Position].ToString()); 
    } 
} 

使用MethodInvocationTarget而不是Method修复了问题。