Menu

ASP.NET Core 2 – reading custom setting from appsettings.json

Asp.net core 2 released recently and I wanted to port my existing asp.net 1.1 app to 2.0. Updated the NuGet packages and most things remain same, but I noticed the reading app settings are broken (well there were few others too – maybe later.)

Imaging this is your appsettings.json file

{
  "Logging": {
    ....................
  },
  "ConnectionStrings": {
   ...................
  },

  "AppSettings": {
    "Secret": "OXOXOXOXOXOXOXOX",
    "TimeZone": "AUS Eastern Standard Time"   
  }
}

Create AppSettings.cs and create properties that represent your app settings

public class AppSettings
{
   public string Secret { get; set; }
   public string TimeZone { get; set; }
}

Use it as below

remember to import the namespace using Microsoft.Extensions.Options;

public class DateExtension 
{
   private readonly AppSettings _appSettings;

   public DateExtension(IOptions<AppSettings> appSettings)
   {
      _appSettings = appSettings.Value;
   }
       
  public string GetTimeZone()
  {
      return _appSettings.TimeZone;
  }        
}

Enjoy Asp.net Core 2.0!!!

Leave a comment