Expert

Coen Adrien van Driel

I'm a software architect and software quality & testing enthusiast. My focus is on using Microsoft technologies from C# to Azure to create awesome products.

I'm also the founder of ExpertSwitch, a software consulting company.

Accessing Your AppSettings.json And Using Strongly Typed Settings In ASP.NET Core MVC

April 03, 2019

The new way of using configuration settings in ASP.NET Core MVC is via an appsettings.json file within your Web project. No more XML configuration files (even though you still can), instead, a modern implementation of a multi-environment configuration system is built into ASP.NET Core MVC.

To use the appsettings.json, let’s do a short configuration of the Startup.cs class

    public Startup(IHostingEnvironment env, IHostingEnvironment appEnv)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    private IConfiguration Configuration { get; }
And our appsettings.json
    {
        "AppSettings": {
            "MySetting": "IAmASetting",
        },
        "ConnectionStrings": {
            "MyConnection": "IAmAConnection",
        }
    }

Having our configuration all set up, we can then access our appsettings.json via one of two ways, the magic string way, and the strongly typed way. Let’s explore both options.

Directly Accessing AppSettings.json Using Magic Strings

Magic strings are bad..but..if you really want to read your appsettings.json directly, you can pass the key of the setting as a string to the IConfiguration class. This class is by default added to the Dependency Injection register in ASP.NET Core, so if you add it to your controller constructor parameters as below, it should work immediately. The same goes for reading the ConnectionString items.

        public ApiController(IConfiguration configuration)
        {
            string result = configuration["AppSettings:MySetting"];
            //or
            string result2 = configuration.GetValue<string>("AppSettings:MySetting");
            //same for connectionstrings
            string result3 = configuration["ConnectionStrings:MyConnection"];
        }

Note: older versions of ASP.NET Core required you to manually add the IConfiguration to ConfigureServices() as a service as shown below, but this is now built in.

    //OBSOLETE, NOW HAPPENS AUTOMATICALLY, DO NOT ADD
    services.AddSingleton<IConfiguration>(Configuration);

Accessing AppSettings.json The Strongly Typed Way

The preferable way of accessing your settings is by using a simple POCO class representing your settings. This way you won’t risk making any typos and makes programming a lot easier as you can now use Visual Studio's IntelliSense. Having set up the Startup.cs class as shown in the beginning, all we need to create now is an AppSettings.cs class with properties that reflect the items in appsettings.json.

    public class AppSettings
    {
        public string MySetting { get; set; }
    }

After we have created the AppSettings.cs class, we go back to Startup.cs and the following line to the ConfigureServices() method.

    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

This line links up our AppSettings.cs with our appsettings.json, and makes it available for constructor injection in our controllers. In my case the method now looks like this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
    }

Then in our controller we simply add IOptions to our constructor parameters and we are ready to go.

    public ApiController(IOptions<AppSettings>appSettings)
    {
        Settings = appSettings.Value;
    }

    private AppSettings Settings { get; set; }

    public string MyMethod()
    {
        string mySetting = Settings.mySetting;
        return mySetting;
    }

In case you want to access your ConnectionString section strongly typed as well, you can simple create an additional ConnectionStrings.cs class contain the same items as your ConnectionString-section. Set up the rest of you code in an identical way as shown before, but now reference your new ConnectionString.cs class. See the completed code below if you are using both the AppSettings and the ConnectionStrings.

Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
        services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    }
ApiController.cs
    public ApiController(IOptions<AppSettings>appSettings, IOptions<ConnectionStrings> connectionStrings)
    {
        Settings = appSettings.Value;
        Connections = connectionStrings.Value;
    }

    private ConnectionStrings Connections { get; set; }

    private AppSettings Settings { get; set; }
ConnectionStrings.cs
    public class ConnectionStrings
    {
        public string MyConnection { get; set; }
    }

Thanks for reading!

If you want to stay in the loop when I post new articles, follow me on facebookFacebook or twitterTwitter Was this article helpful or do you have any questions? Leave a comment!

Check out other similar articles