Search code examples
azureasp.net-coreapplication-settingsasp.net-core-2.0azure-web-app-service

Get Azure AppSettings in a Controller


I have an ASP.NET Core 2 application hosted on Azure, and I added a new Application Settings MyNewSetting for my App in the Azure Portal.

How do I access that setting from a controller?

My code bellow:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();

    services.Configure<AppSecrets>(Configuration);
    services.AddSingleton<ITableRepositories, TableClientOperationsService>();
    //...

My Controller:

public class RecordController : Controller
{
    const int MyNewSetting = 7; // this one to replace with Azure Setting one
    private readonly ITableRepositories repository;

    public RecordController(ITableRepositories rep) {
        repository = rep;
    }

Here, I need probably to add FromServices injection, but I am not sure if it will work...

EDIT:

Folowing the @dee_zg answer, the following code could probably do the job:

public class RecordController : Controller
{
    int MyNewSetting = 7;
    private readonly ITableRepositories repository;

    public RecordController(ITableRepositories rep) {
        repository = rep;
        int myInt;
        if (int.TryParse(System.Environment.GetEnvironmentVariable("MY_NEW_SETTING"), 
                         out myInt)) {
            MyNewSetting = myInt;
        };
    }

Solution

  • You can choose to either get them from AppSettings["your-key"] collection or as environment variables: Environment.GetEnvironmentVariable("your-key").

    From there you can map them to your custom IOptions and inject wherever you need them.