【问题标题】:.net core authorize Roles do not use magic string.net 核心授权角色不使用魔术字符串
【发布时间】:2021-11-09 15:29:19
【问题描述】:

这是我的代码。但不工作

[Authorize(Roles = nameof(SD.ROLE_ADMIN))]
    [HttpPost]
    public async Task<IActionResult> DeleteUserAsync([FromBody] ManagementUserRequestDTO requestDTO)
    {
        var responseDTO = await _accountRepository.DeleteUser(requestDTO);

        if (responseDTO.IsSucceeded)
            return Ok(responseDTO);

        return BadRequest(responseDTO);
    }

如果将 [Authorize(Roles = nameof(SD.ROLE_ADMIN))] 更改为 [Authorize(Roles = "admin")] 它工作正常

SD.ROLE_Admin -----> 公共静态字符串 ROLE_ADMIN {get; set;} = "admin" 在静态类

如何解决?谢谢。

【问题讨论】:

    标签: entity-framework asp.net-core authorize-attribute magic-string


    【解决方案1】:

    nameof(SD.ROLE_ADMIN) 等于 "ROLE_ADMIN" 并且您的角色名称是 "admin",如果您更改为 [Authorize(Roles = SD.ROLE_ADMIN)] 就足够了

    您需要将public static string ROLE_ADMIN {get; set;} = "admin" 更改为public const string ROLE_ADMIN = "admin"。它必须是一个常量表达式。

    【讨论】:

    • 它不起作用。 [Authorize(Roles = SD.ROLE_ADMIN)] show warnning CS0182: An attribute argument must be an constant expression, typeof expression or array creation expression of an attribute parameter type 所以我添加了nameof
    • @otterotter 更新了答案,你可以将静态字符串更改为常量字符串。
    • 非常感谢!!
    猜你喜欢
    • 2019-03-02
    • 2019-10-13
    • 1970-01-01
    • 2022-01-25
    • 2020-02-16
    • 2018-03-13
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多