2

这可能是重复的,但我找不到我正在寻找的问题,所以我在问它。如何测试一个方法参数是用一个属性装饰的?

你如何测试方法参数是用attribte装饰的?例如,下面的MVC操作方法,使用FluentValidation的CustomizeValidatorAttribute

[HttpPost] 
[OutputCache(VaryByParam = "*", Duration = 1800)] 
public virtual ActionResult ValidateSomeField(
    [CustomizeValidator(Properties = "SomeField")] MyViewModel model) 
{ 
    // code 
} 

我敢肯定,我不得不强类型的lambda表达式使用反射,希望。但不知道从哪里开始。

回答

3

一旦你了解了通过反射一个GetMethodInfo调用方法的手柄,你可以简单地调用GetParameters()对方法,然后对每个参数,您可以检查GetCustomAttributes()呼吁X类型的情况下,例如:

Expression<Func<MyController, ActionResult>> methodExpression = 
    m => m.ValidateSomeField(null); 
MethodCallExpression methodCall = (MethodCallExpression)methodExpression.Body; 
MethodInfo methodInfo = methodCall.Method; 

var doesTheMethodContainAttribute = methodInfo.GetParameters() 
     .Any(p => p.GetCustomAttributes(false) 
      .Any(a => a is CustomizeValidatorAttribute))); 

Assert.IsTrue(doesTheMethodContainAttribute); 

例如,此测试会告诉您是否有任何参数包含该属性。如果您想要一个特定的参数,您需要将GetParameters调用更改为更具体的调用。

+0

感谢您的快速回答。我编辑了这个问题以提供获取MethodInfo的示例代码。 – danludwig 2012-04-18 02:45:09

相关问题