c# - 使用反射执行审计

标签 c# asp.net-mvc vb.net reflection

我想执行审计作为单元测试的一部分,使用反射来验证一些假设,基本伪代码如下:

  1. 对于给定程序集中的每个类, 找到 Controller 类 (ASP.NET MVC2)。

  2. 对于这个类中的每个 Action , 找到任何装饰有 给定的属性(让我们称之为 目标属性)

  3. 为每一个方法装饰 具有感兴趣的属性, 确保至少其中之一 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/

相关文章:

C# 将 ReadOnlyMemory<byte> 转换为 byte[]

c# - 如何使用 ASP.NET MVC Core 初始设置角色和用户(如站点管理员)?

jquery - 级联下拉菜单 MVC 3

VB.NET linq 扩展方法(例如 ToList)不适用于泛型

c# - 在大型 wpf 数据网格中移动/隐藏列的性能问题

c# - Thread.Sleep 的替代品

c# - HttpClientFactory BadRequest?

javascript - 进度条问题

vb.net - 通过 HTTPS 的 wsHTTPBinding 导致错误 400 'Bad Request'

vb.net - 捕获 CTRL+V 或粘贴到 .NET 中的文本框中