问题描述
我正在写将验证验证码的属性.为了正常工作,它需要知道秘密,我将其保存在设置中(秘密管理器工具).但是我不知道如何从属性类读取配置. asp.net核心中的DI支持构造函数注入(并且不支持属性注入),因此会产生编译错误:
I am writing attribute that will verify captcha. In order to work correctly it needs to know secret, which I keep in the settings (Secret manager tool). However I don't know how to read config from the attribute class. DI in asp.net core supports constructor injection (and property injection is not supported), so this will give compilation error:
public ValidateReCaptchaAttribute(IConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
this.m_configuration = configuration;
}
因为我用[ValidateReCaptcha]
装饰方法时无法通过config
because when I decorate method with [ValidateReCaptcha]
I can't pass config
那么如何从属性类中的方法中读取config中的内容?
So how do I can read something from config from the method in attribute class?
推荐答案
您可以使用ServiceFilter attribute
,此博客文章和 asp.net文档.
[ServiceFilter(typeof(ValidateReCaptchaAttribute))]
public IActionResult SomeAction()
在Startup
public void ConfigureServices(IServiceCollection services)
{
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<CaptchaSettings>(Configuration.GetSection("CaptchaSettings"));
services.AddScoped<ValidateReCaptchaAttribute>();
...
}
和ValidateReCaptchaAttribute
public class ValidateReCaptchaAttribute : ActionFilterAttribute
{
private readonly CaptchaSettings _settings;
public ValidateReCaptchaAttribute(IOptions<CaptchaSettings> options)
{
_settings = options.Value;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
...
base.OnActionExecuting(context);
}
}
这篇关于在asp.net核心rc2应用程序的ActionFilterAttribute中访问IConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!