我想执行审计作为单元测试的一部分,使用反射来验证一些假设,基本伪代码如下:
对于给定程序集中的每个类, 找到 Controller 类 (ASP.NET MVC2)。
对于这个类中的每个 Action , 找到任何装饰有 给定的属性(让我们称之为
目标属性
)为每一个方法装饰 具有感兴趣的属性, 确保至少其中之一 action 方法的参数实现给定的 接口(interface)(让我们称之为
ITarget
).
我将如何执行此类检查? (欢迎使用 C# 或 VB.NET 回答)
编辑:
我在这里发布执行此检查的最终代码(已翻译为 VB.NET):
Dim ass As Assembly = Assembly.GetAssembly(GetType(Web.WebConfiguratorMarker))
Dim methodsToCheck = ass.GetTypes().
Where(Function(t) t.IsSubclassOf(GetType(Controller))).
SelectMany(Function(t) t.GetMethods()).
Where(Function(m) m.GetCustomAttributes(GetType(AutoValidateJsonModelAttribute), False).Length > 0).
Where(Function(m) m.ReturnType Is GetType(ActionResult)).ToArray()
For Each method In methodsToCheck
Dim implementsIValidatable As Boolean = False
For Each param In method.GetParameters()
If GetType(IValidatable).IsAssignableFrom(param.ParameterType) Then
implementsIValidatable = True
Exit For
End If
Next
Assert.True(implementsIValidatable, String.Format("Controller of type [{0}] has an action [{1}] that is decorated with <AutoValidateJsonModel()> but does not have a IValidatable instance as a param", method.DeclaringType, method.Name))
Next
最佳答案
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var methods = assembly.GetTypes()
.Where(t => t is System.Web.Mvc.Controller)
.SelectMany(t => t.GetMethods())
.Where(m => m.ReturnType is ActionResult)
.Where(m => m.GetCustomAttributes(typeof(TargetAttribute), false).Length > 0)
.ToArray();
bool implementsITarget = false;
foreach(method in methods)
{
foreach(param in method.GetParameters())
{
if(param.ParameterType is ITarget)
{
implementsITarget = true;
break;
}
}
Assert.True(implementsITarget , String.Format("Controller {0} has action {1} that does not implement ITarget but is decorated with TargetAttribute", method.DeclaringType, method.Name) );
implementsITarget = false;
}
关于c# - 使用反射执行审计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154359/