在asp.net核心rc2应用程序的ActionFilterAttribute中访问IConfiguration [英] Access IConfiguration in the ActionFilterAttribute in the asp.net core rc2 application

查看:93
本文介绍了在asp.net核心rc2应用程序的ActionFilterAttribute中访问IConfiguration的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写将验证验证码的属性.为了正常工作,它需要知道秘密,我将其保存在设置中(秘密管理器工具).但是我不知道如何从属性类读取配置. 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆