【问题标题】:Access IConfiguration in the ActionFilterAttribute in the asp.net core rc2 application [duplicate]在 asp.net core rc2 应用程序的 ActionFilterAttribute 中访问 IConfiguration [重复]
【发布时间】:2016-10-18 23:09:46
【问题描述】:

我正在编写将验证验证码的属性。为了正常工作,它需要知道我保存在设置中的秘密(秘密管理器工具)。但是我不知道如何从属性类中读取配置。 asp.net core中的DI支持构造函数注入(不支持属性注入),所以会报编译错误:

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

            this.m_configuration = configuration;
        }

因为当我使用[ValidateReCaptcha] 装饰方法时,我无法通过配置

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

【问题讨论】:

    标签: asp.net asp.net-core


    【解决方案1】:

    您可以使用ServiceFilter attribute,更多信息请参见blog postasp.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);
         }
    }
    

    【讨论】:

    • IOptions 从何而来?那有必要吗?您链接的任何一个文档中都没有提到它。
    • @starmandeluxe 这种机制允许将强类型选项注入服务。您可以在 Rick Strahl 的post 上找到更多信息
    • 谢谢!不幸的是,这种方式对我不起作用。它需要配置对象中的无参数构造函数,在我的内部我需要从 appSettings.json 中获取设置,这需要 IConfigurationRoot 参数。结果是所有字段都为空,因为它似乎没有使用我的参数化构造函数。
    • @starmandeluxe 我无法理解您的问题。发个新帖子就更好了
    • 我想通了。它需要首先使用 services.AddSingleton() 来初始化配置而不是 services.Configure()
    【解决方案2】:

    你应该像这样使用ServiceFilter

    [ServiceFilter(typeof(ValidateReCaptcha))]

    如果你想使用IConfiguration,你应该将它注入ConfigureServices

    services.AddSingleton((provider)=>
    {
         return Configuration;
    });
    

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多