Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read configuration (appsettings) values inside attribute in .NET Core?

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();
     }
}
like image 349
Teslo. Avatar asked Sep 14 '25 15:09

Teslo.


1 Answers

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");
    }
}
like image 59
ergu Avatar answered Sep 17 '25 20:09

ergu