You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core:控制器方法需认证但无需角色授权的配置疑问

解决方案

你需要将[?]替换为**[Authorize]**(不带角色参数的版本)。

控制器级别的[Authorize("Admin, OtherRole")]会对所有未单独指定授权属性的方法生效,要求用户必须拥有Admin或OtherRole角色才能访问。而在GetAll方法上添加不带角色参数的[Authorize],会覆盖控制器的授权规则,仅要求用户完成身份认证即可访问,不限制具体角色。Add方法因为没有单独指定授权属性,会自动继承控制器的角色限制规则。

修改后的完整代码如下:

[Route("api/[controller]")]
[ApiController]
[Authorize("Admin, OtherRole")]
public class MyController : ControllerBase
{
    public MyController()
    {
    }

    [HttpGet("GetAll")]
    [Authorize]
    public async Task<ActionResult<List<RandomType>>> GetAll()
    {
       // returns an action result
    }

    [HttpPost("Add")]
    public async Task<ActionResult<int>> Add([FromBody] SocietyViewModel req)
    {
       // returns an action result and added record's ID       
    }
}

内容的提问来源于stack exchange,提问作者Ahmadreza Mozaffary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:16:02