title: How can I access AppSettings from an ActionFilterAttribute in ASP.NET Core
body: <p>I am currently trying to develop a WebAPI (.NET Core) which has some controller actions that should use HTTP Basic Authentication. To implement this, I have written an ActionFilterAttribute which I can then use in my controller to restrict access to certain actions. This all workes well if I do something like this:</p>
  
  <p><strong>BasicAuthAttribute.cs</strong></p>
  
  <pre><code>public class BasicAuthAttribute : ActionFilterAttribute{
      private string _username { get; set; }
      private string _password { get; set; }
  
      public BasicAuthAttribute(string username, string password) {
          _username = username;
          _password = password;
      }
  
      public override void OnActionExecuting(ActionExecutingContext actionContext) {
      //do Auth check...
      }
  }
  </code></pre>
  
  <p>In the controller I then use it as following:</p>
  
  <p><strong>SomeController.cs</strong>  </p>
  
  <pre><code>[BasicAuth("testuser","testpassword")]
  [HttpGet("{id}")]
  public IActionResult Get(string id) {
      return new ObjectResult("Test");
  }
  </code></pre>
  
  <p>Now I do not want to specify username ond password in SomeController.cs. Instead I would like to store them in appsettings.json. How is it possible to access values stored in appsettings.json in the OnActionExecuting method in the ActionFilterAttribute? </p>
  
  <p>If I change the constructor of BasicAuthAttribute to the following, .Net expects me to pass the settings, which is not possible. Dependency Injection seems not to work here.</p>
  
  <pre><code>public BasicAuthAttribute(IOptions&lt;AppSettings&gt; appSettings) {}
  </code></pre>
  
  <p>Any help or ideas would be appreciated</p>
  
  <p><strong>UPDATE based on  Set's answer:</strong></p>
  
  <p>I ended up changing the attribute to a filter. In case anybody else needs it see the working solution below:</p>
  
  <p><strong>BasicAuthFilter.cs</strong></p>
  
  <pre><code>public class BasicAuthFilter : IActionFilter {
  
      protected AppSettings _settings { get; set; }
  
      public BasicAuthAttribute(IOptions&lt;AppSettings&gt; appSettings) {
          _settings = appSettings;
      }
  
      public void OnActionExecuted(ActionExecutedContext context) {
          //nothing to do here
      }
  
      public override void OnActionExecuting(ActionExecutingContext actionContext) 
      {
          //do Auth check...
      }
  }
  </code></pre>
  
  <p><strong>SomeController.cs</strong></p>
  
  <pre><code>public class SomeController : Controller {
     [TypeFilter(typeof(BasicAuthFilter))]
     [HttpGet("{id}")]
     public IActionResult Get(string id) {
          return new ObjectResult("Test");
     }
  }   
  </code></pre>