• Disclaimer
  • Disclaimer
Home Articles

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

by coenvand April 3, 2019
April 3, 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; }
}
ASP.NET CoreMVC
0
FacebookTwitterLinkedinEmail
previous post
Disabling Caching For System.Net.WebClient In .NET
next post
What Is The VAR Keyword In C# and Best Practices

You may also like

Setting Up LESS In ASP.NET Core

December 26, 2019

Disabling Caching For System.Net.WebClient In .NET

April 3, 2019

Forwarding Domain Names with ASP.NET Core and Azure...

January 14, 2019

Leave a Comment Cancel Reply

Save my name, email, and website in this browser for the next time I comment.

Coen Adrien van Driel

I'm an Azure Cloud & DevOps Consultant with a software development background. I mainly focus on Microsoft technologies.

Need help?

If you need help with your project regarding Azure Cloud & DevOps maybe I can help. Feel free to send me an email.

Socials

Facebook Twitter Linkedin Github

Tags

ASP.NET Core (4) Azure (8) Azure Compute (1) Azure Storage (4) Azure Web Apps (1) C# (1) Content Delivery Network (1) CSS (1) DirectX (1) Gulp (1) LESS (1) MVC (1) OpenGL (1) Virtual Machine (3) Visual Studio (1) WebClient (1)
  • Facebook
  • Twitter
  • Linkedin
  • Email
  • Github

@2020 - All Right Reserved. Disclaimer


Back To Top