2016-06-17 15 views
2

私はcaptchaを検証する属性を書いています。正しく動作させるためには、シークレットを知っておく必要があります(シークレットマネージャツール)。しかし、私は属性クラスから設定を読み込む方法を知らない。 asp.netコアにおけるDIは(とプロパティインジェクションがサポートされていない)コンストラクタ・インジェクションをサポートしていますので、これはコンパイルエラーを与える:asp.netコアrc2アプリケーションのActionFilterAttributeのIConfigurationにアクセス

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

      this.m_configuration = configuration; 
     } 

私は[ValidateReCaptcha]とメソッドを飾るとき、私はそう設定

を渡すことはできませんので、属性クラスのメソッドからconfigから何かを読むことができますか?

答えて

4

あなたはServiceFilter attributeを使用することができ、この中に詳細情報をblog postおよびasp.net docsStartup

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>(); 
     ... 
} 

そしてIOptionsから来たん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); 
    } 
} 
+0

[ServiceFilter(typeof(ValidateReCaptchaAttribute))] public IActionResult SomeAction() 

?それは必要ですか?リンクしたドキュメントのいずれにも言及していません。 – starmandeluxe

+0

@starmandeluxeこのメカニズムにより、強力な型指定されたオプションをサービスに注入できます。 Rick Strahlの[post](https://weblog.west-wind.com/posts/2016/may/23/strongly-typed-configuration-settings-in-aspnet-core)で詳しい情報を見つけることができます – tmg

+0

ありがとうございました!残念ながら、それは私のためにこのようには機能しません。それは設定オブジェクトにパラメータのないコンストラクタを必要とし、私の内部では、IConfigurationRootパラメータを必要とするappSettings.jsonから設定を取得する必要があります。その結果、パラメータ化されたコンストラクタを使用していないように見えるため、すべてのフィールドがnullになります。 – starmandeluxe

2

あなたはこのようServiceFilterを使用する必要があります。

[ServiceFilter(typeof(ValidateReCaptcha))]

そして、あなたはIConfigurationを使用したい場合は、ConfigureServicesでそれを注入する必要があります

services.AddSingleton((provider)=> 
{ 
    return Configuration; 
}); 
関連する問題