Appsettings.json configuration in ASP.Net Core Web API

ASP.Net Core provides appsettings.json file through which we can maintain all the custom configuration required for the successful execution of application. This is a breaking change compared to previous versions of ASP.Net where web.config is primarily used to hold configuration. Appsettings.json is light weight configuration file where all settings are stored in json format and just like web.config we can have have different configuration files for different environments (do not mistake me this is nothing related to transformations, but rather cascading). Accessing this configuration data can be done through Options pattern and ASP.Net Core provides a default middleware to achieve this functionality. In this tutorial, we will see how to access configuration in appsettings.json file and also how to maintain different config files for different environments (staging, production etc.).

NOTE: Updated this tutorial on 2/26/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

image

Now lets open appsettings.json file and add the following custom setting.

{
  "ApplicationSettings": {
    "TestSetting": "TestValue"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

To get our configuration in a strongly typed object, add the following class to our project.

public class ApplicationSettings
{
    public string TestSetting { get; set; }
}

Now to make the instance of our ApplicationSettings class to hold the actual configuration values, we need to inject IOptions (basically Options pattern injected to every controller, view etc.,) and configure that instance of ApplicationSettings class should give ApplicationSettings section of appsettings.json.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();

    services.AddOptions();
    services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
}

Then in our controller (or in any other components like Views etc.,), we can access the settings in following way.

[Route("api/[controller]")]
public class StudentController : Controller
{
    private IOptions<ApplicationSettings> _settings;
    public StudentController(IOptions<ApplicationSettings> settings)
    {
        _settings = settings;
    }

    [HttpGet("GetSetting", Name = "GetSetting")]
    public IActionResult GetSetting()
    {
        var testSetting = _settings.Value.TestSetting;
        return new ObjectResult(testSetting);
    }
}

When we execute the code (using postman tool), we will get following result.

image
image
Now lets see how we can maintain different configuration files for different environments. Create an appsettings file with name appsettings.production.json at the root of the project. This settings file will act as production environment configuration.

image

Have the following settings in the created file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;"
  },
  "ApplicationSettings": {
    "TestSetting": "ProductionValue"
  }
}

To make use of this file, we have to change the environment variable and point it to production.This change can be done by editing project level properties (right click project –> Properties). Navigate to Debug tab and change ASPNETCORE_ENVIRONMENT variable to Production.

image 

Make sure to have the default ConfigurationBuilder code in Startup.cs. Based on the ASPNETCORE_ENVIRONMENT environment variable, below code will pick up the both appsettings files (appsettings.json and appsettings.production.json) and the second file settings will override the settings of first one for the properties which are available in both, otherwise corresponding settings from each file will be persisted.

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

Now when you the run the same endpoint which we created earlier, you should see the production value.

image

image

That’s it for now. Happy Coding and Stay Tuned!!!

You may also like...

  • ramiramilu

    Which hardcode?