I have a .NET Core 1.1 Application with a custom attribute set on an action in the HomeController. Given the fact that I need a value from configuration file (appsettings.json) inside the attribute logic, is it possible to access configuration at attribute level?
appsettings.json
{
"Api": {
"Url": "http://localhost/api"
}
}
HandleSomethingAttribute.cs
public class HandleSomethingAttribute : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// read the api url somehow from appsettings.json
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
HomeController.cs
public class HomeController: Controller
{
[HandleSomething]
public IActionResult Index()
{
return View();
}
}
I'm doing the same thing. I did something similar to Dzhambazov's solution, but to get the environment name I used Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
. I put this in a static variable in a static class that I can read from anywhere in my project.
public static class AppSettingsConfig
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.Build();
}
I can just call this from the attribute like so:
public class SomeAttribute : Attribute
{
public SomeAttribute()
{
AppSettingsConfig.Configuration.GetValue<bool>("SomeBooleanKey");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With