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

7.7k views Asked by At

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

There are 2 answers

1
Dzhambazov On
public HandleSomethingAttribute ()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");
    Configuration = builder.Build();

    string url = Configuration.GetSection("Api:Url").Value;
}

Hi, try this in the Attribute constructor. It should be working!

0
ergu On

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");
    }
}