0

Is there a reasonably simple way to get FxCop to check whether there is any usage of ViewBag, ViewData in MVC application.

4

1 回答 1

1

最简单的方法是筛选名为“ViewBag”或“ViewData”(带有get_set_前缀)的 MemberBinding 实例。这可能会导致相当多的误报,因此下一个复杂性/完整性级别将是检查 MemberBinding 目标的类型,以查看它是视图还是控制器。例如:

private readonly string[] _forbiddenNames = new string[] { "get_ViewBag", "set_ViewBag", "get_ViewData", "set_ViewData" };

public override ProblemCollection Check(Member member)
{
    var method = member as Method;
    if (method != null)
    {
        this.Visit(method.Body);
    }

    return this.Problems;
}

public override void VisitMemberBinding(MemberBinding memberBinding)
{
    base.VisitMemberBinding(memberBinding);

    var memberName = memberBinding.BoundMember.Name.Name;
    if (this._forbiddenNames.Contains(memberName))
    {
        this.Problems.Add(new Problem(this.GetResolution(memberBinding.BoundMember), memberBinding, memberName));
    }
}
于 2013-06-05T15:02:42.973 回答