【问题标题】:Call config setting in action filter attribute在动作过滤器属性中调用配置设置
【发布时间】:2021-11-03 09:32:32
【问题描述】:

谁能帮我解决这个问题?我被告知我不能将 Key/Credentials 保留在控制器中,所以我尝试从配置文件中检索它并能够打印该值,但我无法在操作过滤器属性中使用它

[HttpPost]
[CaptchaValidator(PrivateKey ="123")] //This works
[CaptchaValidator(PrivateKey = System.Configuration.ConfigurationManager.AppSettings["myKey"])] //Error "Argument must be constant expression"
public ViewResult myForm() 
{
//...
}

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    你最好找到一种方法在 CaptchaValidator 的构造函数中注入配置读取 所以,它应该看起来像

    public sealed class CaptchaValidator : ActionFilterAttribute 
    {
        private readonly field _secretConfiguration;
        public CaptchaValidator(SecretConfiguration secretConfiguration) 
        {
            _secretConfiguration = secretConfiguration;
        }
    
        // do OnActionExecuting override and implement reading keys from_secretConfiguration
    }
    

    这里提供了很好的例子:How can I use Dependency Injection in a .Net Core ActionFilterAttribute?

    请注意,最受好评的评论中使用的方法比接受的答案更好,因为接受的答案代表 ServiceLocator(反)模式。

    很遗憾,您确实不能在属性的编译时设置中传递运行时计算的字符串。

    【讨论】:

    • 感谢您的回复。由于我是新手,如果您能解释如何使用上面的代码来匹配我的场景,那就太好了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    相关资源
    最近更新 更多