![](/img/trans.png)
[英]Flag Role Enum with JWT Bearer Token and Custom AuthorizeAttribute
[英]AuthorizeAttribute Implicitly Typed populated role with enum
我在枚舉中扮演角色
public enum Role
{
Undefined = 0,
Public= 1,
Private = 2,
..... list continues...
}
我正在使用AuthoriseAtribute for API設置訪問權限
[HttpGet]
[AuthoriseUser(AllowedRoles = new[] { Role.Private, Role.Public })]
public <anyreturnType> Get(int id)
{
// some stuff
}
哪個工作正常。 但是我喜歡使其更具動態性並優化代碼,因此我沒有寫完整的一長串角色。
因此,我正在努力實現這一目標。
[HttpGet]
[AuthoriseUser(AllowedRoles = new[] { All Roles except Undefined })]
public <anyreturnType> Get(int id)
{
// some stuff
}
這是我創建的解決方案,它不起作用。
[HttpGet]
[AuthoriseUser( AllowedRoles = new[] { Enum.GetNames(typeof(Role)).Cast<Role>().Where(r => r != Role.Undefined) } )]
public <anyreturnType> Get(int id)
{
// some stuff
}
我得到的錯誤是
錯誤CS0029無法將類型'System.Collections.Generic.IEnumerable []'隱式轉換為'Model.Role []'
AuthoriseUserAttribute類看起來像這樣。
public class AuthoriseUserAttribute : AuthorizeAttribute
{
public Role[] AllowedRoles { get; set; }
.....more stuff here....
}
當我使用@Camilo Terevinto推薦的解決方案以及@ejohnson進一步推薦的解決方案時,出現以下錯誤
Camilo Terevinto是正確的,除了您還需要使用Enum.GetValues
而不是Enum.GetNames
(它返回字符串):
Enum.GetValues(typeof(Role)).Cast<Role>().Where(r => r != Role.Undefined).ToArray()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.