【问题标题】:Web Api - Authorization on a per-user basis using annotationsWeb Api - 使用注释对每个用户进行授权
【发布时间】:2026-01-17 11:50:01
【问题描述】:

是否可以使用注解实现基于用户的授权过程? 我正在构建一个 REST Api,我希望用户只能访问属于他们的项目。这是通过查看传输的包含用户 ID 的 AccessToken 来实现的,从中我可以判断用户是否有权查看请求的内容。

为了避免每个 Controller.Method() 中的静态授权过程,我非常想使用这样的 AuthorizationAttribute:

[RestrictAccess(Access.ADMIN, Access.OWNER)]
public SensitiveData GetSensitiveData(Guid userId) {

     return Repository.GetSensitiveData(userId);

}

例如,应该只允许所有具有 AccessRole ADMIN 和所请求项目的 OWNER 的用户调用此方法。

基本上我正在寻找一种在运行时在我的 AuthorizationAttribute 中使用控制器参数的方法。这可能吗?

谢谢!

【问题讨论】:

    标签: authorization asp.net-web-api roles custom-attributes


    【解决方案1】:

    我找到了解决办法:

    using System.Web.Http.Filters;
    public class Restriction : ActionFilterAttribute {
    
        public override void OnActionExecuting(HttpActionContext actionContext) {
    
            // holds a dictionary of arguments passed to annotated Controller.
            var arguments = actionContext.ActionArguments; 
    
            base.OnActionExecuting
    
        }
    
    }
    

    【讨论】:

    • 这对你有用吗?我的 ActionArguments 没有得到我传递给控制器​​的参数的副本....