代码之家  ›  专栏  ›  技术社区  ›  vmg

访问asp中ActionFilterAttribute中的IConfiguration。net core rc2应用程序[重复]

  •  10
  • vmg  · 技术社区  · 9 年前

    我正在编写验证captcha的属性。为了正确工作,它需要知道我保存在设置中的秘密(秘密管理器工具)。但是,我不知道如何从属性类读取config。asp中的DI。net core支持构造函数注入(不支持属性注入),因此这将导致编译错误:

    public ValidateReCaptchaAttribute(IConfiguration configuration)
            {
                if (configuration == null)
                {
                    throw new ArgumentNullException("configuration");
                }
    
                this.m_configuration = configuration;
            }
    

    因为当我用 [ValidateReCaptcha] 我无法传递配置

    那么,如何从属性类中的方法读取config中的内容呢?

    2 回复  |  直到 9 年前
        1
  •  15
  •   tmg    9 年前

    你可以使用 ServiceFilter attribute ,此中的更多信息 blog post asp.net docs .

    [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);
         }
    }
    
        2
  •  5
  •   adem caglin    9 年前

    你应该使用 ServiceFilter 这样地:

    [ServiceFilter(typeof(ValidateReCaptcha))]

    如果你想使用 IConfiguration 你应该把它注射进去 ConfigureServices :

    services.AddSingleton((provider)=>
    {
         return Configuration;
    });
    
    推荐文章