Getting value from appsettings.json in .net core

Using C# & .net Core 2.0 the below code would get the value from app settings.

For example if you have your connections strings defined in your appSettings.json file. Like below:

{
 "AppSettings": {
  "ConnectionStrings": {
   "Test": "Data Source=Test\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI;",
   "UAT": "Data Source=UAT\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI;",
   "Prod": "Data Source=Prod\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=SSPI;"
  }
 }
}

Define your AppSettings Model as: 

 public class AppSettings
 {
   public ConnectionStrings ConnectionStrings { get; set; }        
 }
 public class ConnectionStrings
 {
   public string Test { get; set; }
   public string Uat { get; set; }
   public string Prod { get; set; }
 }

And your startup class as:

  public class Startup
  {
        public IConfiguration Configuration { get; private set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }  

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure(Configuration.GetSection("AppSettings"));
        }
   }

Finally for example if in you home controller you want these values:

  public class HomeController : Controller
  {
        private readonly AppSettings _appSettings;

        public HomeController(IOptions appSettings)
        {
            _appSettings = appSettings.Value;
        }

        public IActionResult Index()
        {
            //Here we can get the app settings value
             var appSettingsValue = _appSettings.ConnectionStrings.Test;
            return View();
        }
   }

No Comments