在授权属性上例外

本文关键字:属性 授权 | 更新日期: 2023-09-27 18:36:33

我有一个有很多操作的控制器。除一项操作外,某些用户只能访问所有操作:

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        return View(...);
    }
    ...
}

即使[Authorize (Roles = null)]也不起作用。方法属性将被忽略!如何仅获得一个操作的异常?就像AllowAnonymous允许它但对登录用户可见一样?

在授权属性上例外

你可以像我在下面的代码中一样使用OverrideAuthorization属性:

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
    [OverrideAuthorization]
    [Authorize()]
    public ActionResult Index()
    {
        return View(...);
    }
    ...
}

使用 MVC5 附带[OverrideAuthorization] ASP.Net 您可以告诉Index操作覆盖/忽略在控制器级别定义的授权规则。

通过执行此操作,您在SecretsController中定义的所有操作仅对管理员角色可见,但Index操作除外,即使他们不是管理员角色,也仅对经过身份验证的用户可见。

使用属性 AllowAnonymous

[Authorize(Roles = "Admin")]
public class SecretsController : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View(...);
    }
    ...
}

编辑由于该问题是在我回答后立即编辑的,因此准确地提到不想要匿名选项

就像允许匿名允许它但对登录用户可见一样?

最好的答案现在是CodeNotFound的答案