c# - 如何从 Web.config 获取常量字符串?

标签 c# asp.net-mvc entity-framework authorization constants

为了在 Entity Framework 应用程序中进行授权,我编写了此类来检查当前用户是否属于指定角色。

public class AuthorizeDesignatedRoles : AuthorizeAttribute {

        public const string DELETE = System.Configuration.ConfigurationManager.AppSettings["GroupAuthorizedForDeleteAction"].ToString();
        public string DesignatedRoles { get; set; }

        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) {
            bool isAuthorizedBase = base.IsAuthorized(actionContext);
            if (!isAuthorizedBase)
                return false;


            string[] roles = DesignatedRoles.Split(';');  // Multiple roles can be seperated by a semicolon ;
            foreach (string role in roles) {
                if (System.Web.Security.Roles.IsUserInRole(role))
                    return true;
            }
            return false;
        }

    }

现在我可以只允许具有指定角色的用户执行 Controller 操作。

[AuthorizeDesignatedRoles(DesignatedRoles = AuthorizeDesignatedRoles.DELETE)]
public HttpResponseMessage DeleteThisAndThat(long id) { ... }

问题是我不想把指定的DELETE组的名字放在代码里而是放在web.config文件里。通过这样做,Visual Studio 会提示它不再是常量字符串。

如何使它再次成为常量字符串?

编辑:当我省略 const 关键字并改用 DELETE static readonly 时,编译器说 An attribute argument must可以是属性参数类型的常量表达式、typeof表达式或数组创建表达式。

最佳答案

如何将 AppSettings 键存储在常量中并在 IsAuthorized 方法中获取它的值:

public class AuthorizeDesignatedRoles : AuthorizeAttribute
{
    public const string DELETE = "GroupAuthorizedForDeleteAction";

    public string DesignatedRoles { get; set; }

    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) {
    {
        // ...

        string[] roles = DesignatedRoles.Split(';')
                                        .Select(s => ConfigurationManager.AppSettings[s].ToString())
                                        .ToArray();

        foreach (string role in roles)
        {
            // ...
        }
    }
}

关于c# - 如何从 Web.config 获取常量字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22295152/

相关文章:

C#/Mono Console.In.ReadToEnd() 停止进程

c# - 如何访问 .URL 文件中的 URL 和书签标题?

c# - 如何让浏览器后退按钮通过 AJAX 调用带你返回?

c# - 使用 ASP.NET MVC 和 SqlMembershipProvider 在哪里存储额外的用户详细信息?

entity-framework - 在 Flutter 中从相机创建故事

entity-framework - 将 EF Code First 同步到 SQL Azure

c# - 为什么这个 CompiledQuery 没有提供性能改进?

C# 优先级列表

c# - 使用 HTMLAgilityPack 进行 XHTML 解析

c# - KENDO ui menU IE9问题