测试 MVC 控制器方法上的属性数量

Testing the number of attributes on an MVC controller method

我有一个包含以下 post 方法的 MVC 控制器:

[HttpPost]
[PermissionLevel(PermissionLevel.Manage)]
public async Task<IActionResult> CreateUserAsync([FromBody] User user)
{
    user = await _usersService.CreateUserAsync(user);

    return Created($"{_microservices.Users}/{user.Id}", user);
}

我正在尝试对该控制器进行单元测试(使用 MSTest),并且我要进行的测试之一是检查是否已将正确的路由和权限属性应用于该方法。我还想确保 方法上没有其他 属性,我目前正在通过检查方法上的属性计数来做到这一点:

[TestMethod]
public void CreateUserAsync_HasTwoAttributes()
{
    int count = typeof(UsersController).GetMethod(nameof(UsersController.CreateUserAsync))
        .GetCustomAttributes()
        .Count();

    Assert.AreEqual(2, count);
}

这在我的应用程序的其他地方(对于属性)工作得很好,但是当我 运行 测试断言失败时说该方法实际上有 4 个属性:

AsyncStateMachine-DebuggerStepThrough- 属性从何而来?有没有一种方法我可以不包含它们而只查看在控制器方法上显式声明的属性?

我正在使用:

任何帮助将不胜感激:)

Where do the AsyncStateMachine- and DebuggerStepThrough- attributes come from?

这些额外的属性是在编译时添加的。异步添加 AsyncStateMachineAttribute

When a method (MethodName) has the Async or async modifier, the compiler emits IL that includes a state machine structure. This structure contains the code in the method. That IL also contains a stub method (MethodName) that calls into the state machine. The compiler adds the AsyncStateMachine attribute to the stub method so that tools can identify the corresponding state machine. Details of the emitted IL might change in future releases of the compilers.

和调试模式添加 other.