我有两个动作具有相同的路由路径,我需要根据用户的权限执行每个动作。
我写的代码不起作用。它说:AmbiguousActionException: Multiple actions matched.
这是动作:
[HttpPost("info"), Authorize("only-boxer")]
public async Task<IActionResult> EditProfile([FromBody]BoxerProfileInfoEditModel model)
{
// do one thing...
}
[HttpPost("info"), Authorize("only-manager")]
public async Task<IActionResult> EditProfile([FromBody]ManagerProfileInfoEditModel model)
{
// do another thing...
}
这就是我注册策略的方式:
services.AddAuthorization(options =>
{
options.AddPolicy("only-boxer", policy =>
{
policy.RequireRole("boxer");
});
options.AddPolicy("only-manager", policy =>
{
policy.RequireRole("manager", "promoter");
});
});
我应该一次检查权限并手动提取数据,还是有其他更整洁的方式?
答案 0 :(得分:0)
我不知道此解决方案是否合适,但 here我了解动作约束,并撰写了自己的动作约束
public class RoleAttribute : Attribute, IActionConstraint
{
public int Order => 0;
private string[] _roles;
public RoleAttribute(params string[] roles)
{
_roles = roles;
}
public bool Accept(ActionConstraintContext context)
{
var user = context.RouteContext.HttpContext.User;
var role = user.FindFirst("role-name").Value;
return _roles.Contains(role);
}
}
现在,这正在起作用。
[HttpPost("info"), Authorize, Role("boxer")]
public async Task<IActionResult> EditProfile([FromBody]BoxerProfileInfoEditModel model)
{
// do one thing...
}
[HttpPost("info"), Authorize, Role("manager", "promoter")]
public async Task<IActionResult> EditProfile([FromBody]ManagerProfileInfoEditModel model)
{
// do another thing...
}
如果您能分享自己对执行此操作的想法或其他解决方案,我将不胜感激。