ASP.NET Core for Beginners – Utilizing Configuration Properties From The appsettings.json File

This post is part of a series for helping beginners get started with ASP.NET Core. You can find an updated list of topics in this series here.

In this post, we will learn how to read a simple value from a configuration file in ASP.NET Core.

Getting Started

You will need to set up a new ASP.NET Core project. You can learn the specifics of that in the ASP.NET Core Series page linked to above in the post titled ASP.NET Core Project Setup.

Background

In order to get the most from this post, you should have a basic understanding of how dependency injection works in ASP.NET Core. It is important because we need access to the IConfiguration service in the Configure method of the application’s Startup.cs file.

If you are coming from a previous non-Core version of ASP.NET, you are accustomed to using the web.config file for application configuration. The web.config file has been replaced with the appsettings.json file. In case it isn’t plain, settings are no longer stored in XML. Now, we use JSON. The IConfiguration service unlocks the ability for us to use a variety of sources for configuration.

  1. Command Line Arguments
  2. Environment Variables
  3. Application Configuration (appsettings.json)
  4. User Secrets

Listing 1.1 – Configure Method Signature Changes

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

So far, the only change is the IConfiguration configuration declaration. This will require you to add a reference to the Microsoft.Extensions.Configuration namespace.

Listing 1.2 – appsetttings.json Contents

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*", 
  "Greeting":  "Greetings, Traveler!"
}

The important part here is the Greeting property. This is the value we want to pull out of the configuration file in our Configure method.

Listing 1.3 – Retrieving a Configuration Value

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IConfiguration configuration)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.Run(async (context) =>
    {
        string greeting = configuration["Greeting"];

        await context.Response.WriteAsync(greeting);
    });
}

Finally, we come to it. The greeting variable retrieves the Greeting property from the appsettings.json file and we can then print it out to the browser.

Conclusion

In this post, we looked at how to retrieve configuration values and hopefully learned a bit about how the IConfiguration service works in ASP.NET Core.

Leave a Reply

Your email address will not be published.