为什么授权属性策略参数限于const?

问题描述 投票:0回答:2

为什么将Authorize Attribute策略参数限制为const“ compile time”?

因为此限制不允许使用字符串连接,如下面的示例,所以有任何限制的理由。

 [Authorize($"{Privilege1},{Privilege2}")]
 [HttpPost()]
 public async Task<IActionResult> Testpost()
 {
        return Ok();
 }
asp.net .net asp.net-core .net-framework-version asp.net-apicontroller
2个回答
0
投票

属性参数必须在编译时就知道,才能将其放入程序集元数据中。这就是属性的工作方式。在您的情况下,${}表示仅在运行时知道该值。

concatenation无关,您可以放心地将"a" + ",b"放在这里,这显然是一个串联,但仍使用编译时已知的字符串值。

尝试创建your own security policy or inherit the AuthorizeAttribute。在您的自定义逻辑中,您可以引用任何静态或动态角色。


0
投票

是,很遗憾,您不能在常量中使用字符串插值,而必须在AuthorizeAttribute之类的属性中使用常量。内插的字符串在运行时进行内插,并且需要在编译时创建常量。

但是您可以通过这种方式连接字符串,编译器可以将其制成常量:

Authorize
© www.soinside.com 2019 - 2024. All rights reserved.