Tuesday, May 1, 2018

pulling things out of appsettings.json in an ASP.NET Core application

Page 38 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis touches on appsettings.json and the one in the ASP.NET Core application we are building looks like this:

{
   "Logging": {
      "IncludeScopes": false,
      "Debug": {
         "LogLevel": {
            "Default": "Warning"
         }
      },
      "Console": {
         "LogLevel": {
            "Default": "Warning"
         }
      }
   }
}

 
 

WebHost.CreateDefaultBuilder (an ASP.NET Core version 2 thing) back in Program.cs will automatically make appsettings.Development.json as seen below overpower appsettings.json when applicable in development environments only. It is the new Web.Debug.config where as appsettings.json is the new Web.config.

{
   "Logging": {
      "IncludeScopes": false,
      "Debug": {
         "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
         }
      },
      "Console": {
         "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
         }
      }
   }
}

 
 

If you make a constructor for a controller like so, ASP.NET Core 2 will hydrate IConfiguration for you.

public HomeController(IConfiguration configuration)
{
   var myValue = configuration["Logging:IncludeScopes"];
   var whatever = "breakpoint";
}

 
 

If we set a breakpoint at var whatever = "breakpoint"; above we would be able to inspect the myValue variable and see that it was "False" as expected. It is easy to mix your own settings in with the settings that mean something to the canned code I surmise.

 
 

Addendum 5/17/2018: configuration["Logging:IncludeScopes"]; here should probably be Configuration["Logging:IncludeScopes"]; with a capital C.

 
 

Addendum 4/8/2020: Note the use of the colon above to drill into nested stuff at appsettings.json.

No comments:

Post a Comment