在我的 ASP.NET Web API 控制器中,我想限制对用户角色的访问。执行此操作的常用方法是扩展 AuthorizeAttribute ( example , example ),然后使用我的自定义属性 (例如 [AuthorizeUser]) 在我的控制器上撒上。
另一种方法是在控制器的构造函数中添加一个函数。无论如何都需要构造函数,因为我正在使用依赖注入。
这是一些代码:
public class MyController: ApiController
{
private IUnitOfWork unitOfWork;
private IAccountUtils accountUtils;
// Constructor
public MyController(
IUnitOfWork unitOfWork,
IAccountUtils accountUtils)
{
this.unitOfWork = unitOfWork;
this.accountUtils = accountUtils;
// Restrict access to 'User' role
accountUtils.ThrowExceptionIfUserNotInRole(User.Identity, "User");
}
// More code
}
因为有无数的教程和示例使用过滤器来授权用户,所以我认为这是最好的方法。但是,当我在调试器中单步执行我的代码时,我发现构造函数方法在过滤器之前被触发。
为了优化代码,如果用户无权访问控制器,尽快中断是有意义的。如果我没记错的话,在构造函数中而不是在过滤器中执行授权应该更有效。我是正确的还是我在这里遗漏了什么?