这可能是重复的,但我找不到我要找的问题,所以我问它。
如何测试方法参数是否用属性修饰?例如,以下 MVC 操作方法,使用 FluentValidation 的 CustomizeValidatorAttribute
:
[HttpPost]
[OutputCache(VaryByParam = "*", Duration = 1800)]
public virtual ActionResult ValidateSomeField(
[CustomizeValidator(Properties = "SomeField")] MyViewModel model)
{
// code
}
我确信我必须使用反射,希望使用强类型的 lambda。但不知道从哪里开始。
最佳答案
一旦您通过反射通过 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
调用更改为更具体的参数。
关于asp.net-mvc - 如何测试方法参数是否用属性修饰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10197677/