0

Could anyone help me to resolve this issue? I'm told I can not keep Key/Credentials inside the controller so I tried to retrieve it from the config file and was able to print the value but I'm not able to use it inside the action filter attribute

[HttpPost]
[CaptchaValidator(PrivateKey ="123")] //This works
[CaptchaValidator(PrivateKey = System.Configuration.ConfigurationManager.AppSettings["myKey"])] //Error "Argument must be constant expression"
public ViewResult myForm() 
{
//...
}
Raju Ahmed
  • 1,282
  • 5
  • 15
  • 24
Alex Khan
  • 11
  • 2

1 Answers1

1

You probably better find a way to inject the configuration reading in constructor of CaptchaValidator so, it should look like

public sealed class CaptchaValidator : ActionFilterAttribute 
{
    private readonly field _secretConfiguration;
    public CaptchaValidator(SecretConfiguration secretConfiguration) 
    {
        _secretConfiguration = secretConfiguration;
    }

    // do OnActionExecuting override and implement reading keys from_secretConfiguration
}

Good example is provided here: How can I use Dependency Injection in a .Net Core ActionFilterAttribute?

Please, note that approach is used in the most upvoted comment is better than the accepted answer because the accepted answer is representing ServiceLocator (anti)pattern.

Unfortunately, you can't indeed pass Runtime-calculated string in Compile-time setting of attribute.

Vladmir
  • 1,255
  • 9
  • 13
  • Thank you for the response. Since I'm a newbie it would be great if you could explain how to use the above code to match my scenario – Alex Khan Nov 03 '21 at 10:17