Click here to Skip to main content
15,893,668 members
Articles / Web Development / ASP.NET / ASP.NET Core

ASP.NET Core 2.0 Configuration

Rate me:
Please Sign up or sign in to vote.
1.44/5 (5 votes)
9 Oct 2017CPOL2 min read 18.2K   2   3
How to read configuration settings from various sources and use them throughout your application. Continue reading...

Problem

How to read configuration settings from various sources and use them throughout your application.

Solution

Starting from the Empty Project from a previous post, add appsettings.json and appsettings.Development.json files in your project:

C#
// appsettings.json
{
  "Section1": {
    "SettingA": "ValueA",
    "SettingB": "ValueB"
  },
  "Section2": {
    "SettingC": "ValueC"
  }
}
// appsettings.Development.json
{
  "Section1": {
    "SettingA": "Dev_ValueA"
  },
  "Section2": {
    "SettingC": "Dev_ValueC"
  }
}

Then, read configuration settings in the constructor for Startup class:

C#
public static IConfiguration Config { get; private set; }

        public Startup(
            IConfiguration config)
        {
            Config = config;
        }

Then, add option services in ConfigureServicees() method of Startup class:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            // setup dependency injection in service container
            services.AddOptions();
            services.Configure(Config);
        }

Finally, inject settings as IOptions interface, where T is your POCO:

C#
public class HelloWorldMiddleware
    {
        private readonly RequestDelegate next;
        private readonly AppSettings settings;

        public HelloWorldMiddleware(
            RequestDelegate next,
            IOptions<AppSettings> options)
        {
            this.next = next;
            this.settings = options.Value;
        }

        public async Task Invoke(HttpContext context)
        {
            var jsonSettings = JsonConvert.SerializeObject(this.settings);
            await context.Response.WriteAsync(jsonSettings);
        }
    }

Running the sample application gives you following output:

Configuration-Output

Discussion

ASP.NET Core has a simple mechanism to read application settings from various sources like JSON file, Environment variables or even custom data sources. It is also simple to use the settings, thanks to Dependency Injection.

Although it seems like magic (how did your settings got loaded!) ASP.NET Core 2.0 hides the adding of configuration settings behind CreateDefaultBuilder() method of WebHost, in Program.cs. IConfiguration is then added to the service container and is available in the rest of your application, we used this in Startup to add options. To see this, replace the BuildWebHost() method in Program.cs and run the program, you’ll get the same result:

C#
public static IWebHost BuildWebHost(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                           .ConfigureAppConfiguration((context, builder) =>
                           {
                               var env = context.HostingEnvironment;

                               builder.AddJsonFile("appsettings.json", 
                                            optional: true, reloadOnChange: true)
                                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                                            optional: true, reloadOnChange: true);

                               if (env.IsDevelopment())
                               {
                                   var appAssembly = Assembly.Load(
                                       new AssemblyName(env.ApplicationName));
                                   if (appAssembly != null)
                                   {
                                       builder.AddUserSecrets(appAssembly, optional: true);
                                   }
                               }

                               builder.AddEnvironmentVariables();

                               if (args != null)
                               {
                                   builder.AddCommandLine(args);
                               }
                           })
                           .UseStartup<Startup>()
                           .Build();
        }

In the solution above, two JSON file sources are provided. The important thing to remember is that these sources are read sequentially and overwrite settings from the previous source. You could see this in the solution above, the output shows SettingB’s value coming from first settings file whereas the other settings are being overwritten by the second settings file.

Note that a public static property holds IConfiguration instance so that it can be used throughout the application like:

C#
var valueA = Config["Section1:SettingA"];

However, a better approach exists to read the settings, i.e., to read the settings into a typed POCO class and then inject it as dependency into middleware, controllers, etc. In the solution above, I’ve used the middleware from a previous post to demonstrate this pattern.

You can also have POCO classes for various sections in the settings file and read them using GetSection() method on IConfiguration:

C#
services.Configure(Config.GetSection("Section1"));

It’s also possible to populate the settings in code using overload of IServiceCollection.Configure that accepts strongly typed lambda:

C#
services.Configure(options =>
            {
                options.Section1.SettingA = "SomeValue";
            });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionSmall Issue with the Code Missing AppSettings Class Pin
Larry Aultman9-Oct-17 4:04
professionalLarry Aultman9-Oct-17 4:04 
AnswerRe: Small Issue with the Code Missing AppSettings Class Pin
User 10432649-Oct-17 22:00
User 10432649-Oct-17 22:00 
GeneralMy vote of 1 Pin
Member 105062271-Sep-17 6:12
Member 105062271-Sep-17 6:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.