MVC 使用来自静态设置的动态角色授权 class

MVC Authorize with dynamic roles from static setting class

我目前正在开发一个需要供多个客户使用的应用程序,这意味着我必须在应用程序的每次发布之间更改授权标签中的角色。

目前我在静态设置中存储客户特定数据 class

public abstract class Settings
{
    public virtual string ConnectionString { get; internal set; } = "";
    public virtual string SharepointMail { get; internal set; } = "";
    public virtual string SharepointPassword { get; internal set; } = "";
    public virtual string SharepointSite { get; internal set; } = "";
    public virtual string SharepointDocumentLibrary { get; internal set; } = "";
    public virtual int ProjectId { get; internal set; }
    public virtual string SuperUserRole { get; internal set; }
    public virtual string UserRole { get; internal set; } = "";
    public virtual string ContributorRole { get; internal set; } = "";


    private static Settings _instance;
    public static Settings Instance
    {
        get
        {
            if (_instance != null)
                return _instance;

  #if DEBUG
            return _instance = new DebugSettings();
  #elif TCOTEST
            return _instance = new TcoTestSettings();
  #elif TCORELEASE
            return _instance = new TcoReleaseSettings();
  #endif
        }
    }
}

我希望能够为每个配置设置超级用户角色,但 属性 需要保持不变才能用作授权属性。

我该怎么做?

我最终创建了自定义授权属性

public class AuthorizeRoleAttribute : AuthorizeAttribute
{
    public string AccessRole { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }
        switch (AccessRole)
        {
            case "SuperUser":
                return httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            case "User":
                return httpContext.User.IsInRole(Settings.Instance.UserRole) || httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            case "Any":
                return httpContext.User.IsInRole(Settings.Instance.ContributorRole) || httpContext.User.IsInRole(Settings.Instance.UserRole) || httpContext.User.IsInRole(Settings.Instance.SuperUserRole);
            default:
                return false;
        }
    }
}

我可以这样使用:

[AuthorizeRole(AccessRole = "Any")]