In .NET Core 2.x, IConfiguration
is already registered to the DI hence is ready for grab. And normally you would just inject IConfiguration
through constructor injection:
public class MyActionFilter : ActionFilterAttribute
{
private readonly IConfiguration _config;
public MyActionFilter(IConfiguration config)
{
_config = config;
}
}
That would work but that also means when you use the action filter, you need to supply IConfiguration
as one of the parameters:
![enter image description here]()
It would be better if you don't have to provide the dependencies manually.
Use GetService<>
instead
One way to go around it is to get the required service(s) on one of the overrides instead:
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class MyActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var config = context.HttpContext.RequestServices.GetService<IConfiguration>();
string recaptchaVersion = config.GetValue<string>("recaptcha:version");
base.OnActionExecuting(context);
}
}
And if your appsettings.json
has something like this:
{
"recaptcha": {
"secretKey": "xxx",
"siteKey": "xxx",
"version": "v3"
}
}
Then config.GetValue<>
should give you what you want to access
![enter image description here]()