How to read AppSettings values from a .json file in ASP.NET Core

C#asp.net Core.Net CoreConfigurationApp Config

C# Problem Overview


I have set up my AppSettings data in file appsettings/Config .json like this:

{
  "AppSettings": {
        "token": "1234"
    }
}

I have searched online on how to read AppSettings values from .json file, but I could not get anything useful.

I tried:

var configuration = new Configuration();
var appSettings = configuration.Get("AppSettings"); // null
var token = configuration.Get("token"); // null

I know with ASP.NET 4.0 you can do this:

System.Configuration.ConfigurationManager.AppSettings["token"];

But how do I do this in ASP.NET Core?

C# Solutions


Solution 1 - C#

This has had a few twists and turns. I've modified this answer to be up to date with ASP.NET Core 2.0 (as of 26/02/2018).

This is mostly taken from the official documentation:

To work with settings in your ASP.NET application, it is recommended that you only instantiate a Configuration in your application’s Startup class. Then, use the Options pattern to access individual settings. Let's say we have an appsettings.json file that looks like this:

{
  "MyConfig": {
   "ApplicationName": "MyApp",
   "Version": "1.0.0"
   }

}

And we have a POCO object representing the configuration:

public class MyConfig
{
	public string ApplicationName { get; set; }
	public int Version { get; set; }
}

Now we build the configuration in Startup.cs:

public class Startup 
{
	public IConfigurationRoot Configuration { get; set; }

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

Note that appsettings.json will be registered by default in .NET Core 2.0. We can also register an appsettings.{Environment}.json config file per environment if needed.

If we want to inject our configuration to our controllers, we'll need to register it with the runtime. We do so via Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
	services.AddMvc();

	// Add functionality to inject IOptions<T>
	services.AddOptions();
	
	// Add our Config object so it can be injected
	services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}

And we inject it like this:

public class HomeController : Controller
{
	private readonly IOptions<MyConfig> config;

	public HomeController(IOptions<MyConfig> config)
	{
		this.config = config;
	}

	// GET: /<controller>/
	public IActionResult Index() => View(config.Value);
}

The full Startup class:

public class Startup 
{
	public IConfigurationRoot Configuration { get; set; }

	public Startup(IHostingEnvironment env)
	{
		var builder = new ConfigurationBuilder()
			.SetBasePath(env.ContentRootPath)
			.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
			
		Configuration = builder.Build();
	}
	
	public void ConfigureServices(IServiceCollection services)
	{
		services.AddMvc();
	
		// Add functionality to inject IOptions<T>
		services.AddOptions();
		
		// Add our Config object so it can be injected
		services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
	}
}

Solution 2 - C#

First off: The assembly name and namespace of Microsoft.Framework.ConfigurationModel has changed to Microsoft.Framework.Configuration. So you should use: e.g.

"Microsoft.Framework.Configuration.Json": "1.0.0-beta7"

as a dependency in project.json. Use beta5 or 6 if you don't have 7 installed. Then you can do something like this in Startup.cs.

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
     var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddEnvironmentVariables();
     Configuration = configurationBuilder.Build();
}

If you then want to retrieve a variable from the config.json you can get it right away using:

public void Configure(IApplicationBuilder app)
{
    // Add .Value to get the token string
    var token = Configuration.GetSection("AppSettings:token");
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync("This is a token with key (" + token.Key + ") " + token.Value);
    });
}

or you can create a class called AppSettings like this:

public class AppSettings
{
    public string token { get; set; }
}

and configure the services like this:

public void ConfigureServices(IServiceCollection services)
{       
    services.AddMvc();

    services.Configure<MvcOptions>(options =>
    {
        //mvc options
    });

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

and then access it through e.g. a controller like this:

public class HomeController : Controller
{
    private string _token;

    public HomeController(IOptions<AppSettings> settings)
    {
        _token = settings.Options.token;
    }
}

Solution 3 - C#

.NET Core 3.0

Maybe it is not the best way to get a value from appsettings.json, but it is simple and it works in my application!!

###File appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection":****;"
    }

    "AppSettings": {
        "APP_Name": "MT_Service",
        "APP_Version":  "1.0.0"
    }
}

###Controller:

On top:

using Microsoft.Extensions.Configuration;

In your code:

var AppName = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AppSettings")["APP_Name"];

Solution 4 - C#

For .NET Core 2.0, things have changed a little bit. The startup constructor takes a Configuration object as a parameter, So using the ConfigurationBuilder is not required. Here is mine:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<StorageOptions>(Configuration.GetSection("AzureStorageConfig"));
}

My POCO is the StorageOptions object mentioned at the top:

namespace FictionalWebApp.Models
{
	public class StorageOptions
	{
		public String StorageConnectionString { get; set; }
		public String AccountName { get; set; }
		public String AccountKey { get; set; }
		public String DefaultEndpointsProtocol { get; set; }
		public String EndpointSuffix { get; set; }

		public StorageOptions() { }
	}
}

And the configuration is actually a subsection of my appsettings.json file, named AzureStorageConfig:

{
  "ConnectionStrings": {
	"DefaultConnection": "Server=(localdb)\\mssqllocaldb;",
	"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
  },
  "Logging": {
	"IncludeScopes": false,
	"LogLevel": {
	  "Default": "Warning"
	}
  },

  "AzureStorageConfig": {
	"AccountName": "fictionalwebapp",
	"AccountKey": "Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==",
	"DefaultEndpointsProtocol": "https",
	"EndpointSuffix": "core.windows.net",
	"StorageConnectionString": "DefaultEndpointsProtocol=https;AccountName=fictionalwebapp;AccountKey=Cng4Afwlk242-23=-_d2ksa69*2xM0jLUUxoAw==;EndpointSuffix=core.windows.net"
  }
}

The only thing I'll add is that, since the constructor has changed, I haven't tested whether something extra needs to be done for it to load appsettings.<environmentname>.json as opposed to appsettings.json.

Solution 5 - C#

With .NET Core 2.2, and in the simplest way possible...

public IActionResult Index([FromServices] IConfiguration config)
{
    var myValue = config.GetValue<string>("MyKey");
}

appsettings.json is automatically loaded and available through either constructor or action injection, and there's a GetSection method on IConfiguration as well. There isn't any need to alter Startup.cs or Program.cs if all you need is appsettings.json.

Solution 6 - C#

If you just want to get the value of the token then use

Configuration["AppSettings:token"]

Solution 7 - C#

I doubt this is good practice but it's working locally. I'll update this if it fails when I publish/deploy (to an IIS web service).

Step 1 - Add this assembly to the top of your class (in my case, controller class):

using Microsoft.Extensions.Configuration;

Step 2 - Add this or something like it:

var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();

Step 3 - Call your key's value by doing this (returns string):

config["NameOfYourKey"]

Solution 8 - C#

For ASP.NET Core 3.1 you can follow this documentation:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

When you create a new ASP.NET Core 3.1 project or .NET 5 project you will have the following configuration line in Program.cs:

Host.CreateDefaultBuilder(args)

This enables the following:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

This means you can inject IConfiguration and fetch values with a string key, even nested values. Like IConfiguration ["Parent:Child"];

Example:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

Solution 9 - C#

The following works for console applications;

  1. Install the following NuGet packages (.csproj);

     <ItemGroup>
         <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
         <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
         <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
     </ItemGroup>
    
  2. Create appsettings.json at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".

  3. Sample configuration file:

     {
       "AppConfig": {
         "FilePath": "C:\\temp\\logs\\output.txt"
       }
     }
    
  4. Program.cs

    configurationSection.Key and configurationSection.Value will have config properties.

     static void Main(string[] args)
     {
         try
         {
    
             IConfigurationBuilder builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
             IConfigurationRoot configuration = builder.Build();
             // configurationSection.Key => FilePath
             // configurationSection.Value => C:\\temp\\logs\\output.txt
             IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
    
         }
         catch (Exception e)
         {
             Console.WriteLine(e);
         }
     }
    

Solution 10 - C#

This worked for me .Net 5

I have a appsettings.development.json file. I have "Development" environment selected that's why I have settings in my development.json file. You can use appsettings.josn with default environment.

enter image description here

with this configuration

enter image description here

created a class with config properties

enter image description here

Registered my calls in Startup

enter image description here

I can now access in my controller

enter image description here

Solution 11 - C#

For .NET Core 2.0, you can simply:

Declare your key/value pairs in appsettings.json:

{
  "MyKey": "MyValue"
}

Inject the configuration service in startup.cs, and get the value using the service

using Microsoft.Extensions.Configuration;

public class Startup
{
    public void Configure(IConfiguration configuration,
                          ... other injected services
                          )
    {
        app.Run(async (context) =>
        {
            string myValue = configuration["MyKey"];
            await context.Response.WriteAsync(myValue);
        });

Solution 12 - C#

Here's the full use-case for ASP.NET Core!

articles.json

{
  "shownArticlesCount": 3,
  "articles": [
    {
      "title": "My Title 1",
      "thumbnailLink": "example.com/img1.png",
      "authorProfileLink": "example.com/@@alper",
      "authorName": "Alper Ebicoglu",
      "publishDate": "2018-04-17",
      "text": "...",
      "link": "..."
    },
    {
      "title": "My Title 2",
      "thumbnailLink": "example.com/img2.png",
      "authorProfileLink": "example.com/@@alper",
      "authorName": "Alper Ebicoglu",
      "publishDate": "2018-04-17",
      "text": "...",
      "link": "..."
    },
  ]
}

ArticleContainer.cs

public class ArticleContainer
{
    public int ShownArticlesCount { get; set; }

    public List<Article> Articles { get; set; }
}

public class Article
{
    public string Title { get; set; }

    public string ThumbnailLink { get; set; }

    public string AuthorName { get; set; }

    public string AuthorProfileLink { get; set; }

    public DateTime PublishDate { get; set; }

    public string Text { get; set; }

    public string Link { get; set; } 
}

Startup.cs

public class Startup
{
    public IConfigurationRoot ArticleConfiguration { get; set; }

    public Startup(IHostingEnvironment env)
    {
        ArticleConfiguration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("articles.json")
            .Build();
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();

        services.Configure<ArticleContainer>(ArticleConfiguration);
    }
}

Index.cshtml.cs

public class IndexModel : PageModel
{
	public ArticleContainer ArticleContainer { get;set; }
	
	private readonly IOptions<ArticleContainer> _articleContainer;

	public IndexModel(IOptions<ArticleContainer> articleContainer)
	{
		_articleContainer = articleContainer;
	}

	public void OnGet()
	{
		ArticleContainer = _articleContainer.Value;
	}
}

Index.cshtml.cs

<h1>@Model.ArticleContainer.ShownArticlesCount</h1>

Solution 13 - C#

Super late to the party but if someone finds this out.

You can call IConfiguration from Microsoft.Extensions.Configuration;

public static IConfiguration Configuration { get; }
public static string MyAwesomeString = Configuration.GetSection("appSettings")["MyAwesomeString"].ToString();

Solution 14 - C#

Just to complement the Yuval Itzchakov answer.

You can load configuration without builder function, you can just inject it.

public IConfiguration Configuration { get; set; }

public Startup(IConfiguration configuration)
{
   Configuration = configuration;
}

    

Solution 15 - C#

.NET Core 2.1.0

  1. Create the .json file on the root directory
  2. On your code:

> var builder = new ConfigurationBuilder() > .SetBasePath(Directory.GetCurrentDirectory()) > .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

var config = builder.Build();

3. Install the following dependencies:

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json

4. Then, IMPORTANT: Right-click on the appsettings.json file -> click on Properties -> select Copy if newer: enter image description here

  1. Finally, you can do:

    config["key1"]

Considering that my config file will look like this: > { > "ConnectionStrings": "myconnection string here", > "key1": "value here" > }

Solution 16 - C#

They just keep changing things – having just updated Visual Studio and had the whole project bomb, on the road to recovery and the new way looks like this:

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

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

I kept missing this line!

.SetBasePath(env.ContentRootPath)

Solution 17 - C#

In addition to existing answers I'd like to mention that sometimes it might be useful to have extension methods for IConfiguration for simplicity's sake.

I keep JWT config in appsettings.json so my extension methods class looks as follows:

public static class ConfigurationExtensions
{
    public static string GetIssuerSigningKey(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:SecurityKey");
        return result;
    }

    public static string GetValidIssuer(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Issuer");
        return result;
    }

    public static string GetValidAudience(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Authentication:JwtBearer:Audience");
        return result;
    }

    public static string GetDefaultPolicy(this IConfiguration configuration)
    {
        string result = configuration.GetValue<string>("Policies:Default");
        return result;
    }

    public static SymmetricSecurityKey GetSymmetricSecurityKey(this IConfiguration configuration)
    {
        var issuerSigningKey = configuration.GetIssuerSigningKey();
        var data = Encoding.UTF8.GetBytes(issuerSigningKey);
        var result = new SymmetricSecurityKey(data);
        return result;
    }

    public static string[] GetCorsOrigins(this IConfiguration configuration)
    {
        string[] result =
            configuration.GetValue<string>("App:CorsOrigins")
            .Split(",", StringSplitOptions.RemoveEmptyEntries)
            .ToArray();

        return result;
    }
}

It saves you a lot of lines and you just write clean and minimal code:

...
x.TokenValidationParameters = new TokenValidationParameters()
{
    ValidateIssuerSigningKey = true,
    ValidateLifetime = true,
    IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
    ValidAudience = _configuration.GetValidAudience(),
    ValidIssuer = _configuration.GetValidIssuer()
};

It's also possible to register IConfiguration instance as singleton and inject it wherever you need - I use Autofac container here's how you do it:

var appConfiguration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
builder.Register(c => appConfiguration).As<IConfigurationRoot>().SingleInstance();

You can do the same with MS Dependency Injection:

services.AddSingleton<IConfigurationRoot>(appConfiguration);

Solution 18 - C#

Get it inside controller as an object via call Get<YourType>():

public IActionResult Index([FromServices] IConfiguration config)
{
    BillModel model = config.GetSection("Yst.Requisites").Get<BillModel>();
    return View(model);
}

Solution 19 - C#

First you should inject IConfiguration and then for reading from appsettings, you can use one of this methods:

  1. Get a section data

     var redisConfig = configuration.GetSection("RedisConfig");
    
  2. Get a value within a section

     var redisServer = configuration.GetValue<string>("RedisConfig:ServerName");
    
  3. Get nested value within section

     var redisExpireMInutes = configuration.GetValue<int>("RedisConfig:ServerName:ExpireMInutes");
    

Solution 20 - C#

The .NET Core 2.2 way

(No doubt Microsoft will change it again to something completely different in the next .NET version.)

###1. appSettings.json

It may look something like this. Here we will be loading Setting1 and Setting2

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Setting1": "abc",
  "Setting2": 123
}

###2. AppSettings.cs

The POCO class to hold Setting1 and Setting2. We will be loading the appsettings.json into this class object. The structure of the POCO class should match the JSON file, properties may be nested within other properties/classes if desired.

public class AppSettings
{
    public string Setting1 { get; set; }
    public int Setting2 { get; set; }
}

###3 Startup.cs

Load appSettings.json into you AppSettings object and start using it:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        AppSettings settings = new AppSettings();

        Configuration = configuration;
        configuration.Bind(settings);

        // Now start using it
        string setting1 = settings.Setting1;
        int setting2 = settings.Setting2;
    }

Solution 21 - C#

Was this "cheating"? I just made my Configuration in the Startup class static, and then I can access it from anywhere else:

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public static IConfiguration Configuration { get; set; }

Solution 22 - C#

You can try below code. This is working for me.

public class Settings
{
    private static IHttpContextAccessor _HttpContextAccessor;

    public Settings(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {
        _HttpContextAccessor = httpContextAccessor;
    }

    public static IConfigurationBuilder Getbuilder()
    {
        var builder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appsettings.json");
        return builder;
    }

    public static string GetAppSetting(string key)
    {
        //return Convert.ToString(ConfigurationManager.AppSettings[key]);
        var builder = Getbuilder();
        var GetAppStringData = builder.Build().GetValue<string>("AppSettings:" + key);
        return GetAppStringData;
    }

    public static string GetConnectionString(string key="DefaultName")
    {
        var builder = Getbuilder();
        var ConnectionString = builder.Build().GetValue<string>("ConnectionStrings:"+key);
        return ConnectionString;
    }
}

Here I have created one class to get connection string and app settings.

I Startup.cs file you need to register class as below.

public class Startup
{

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        Settings.Configure(httpContextAccessor);
    }
}

Solution 23 - C#

In addition to Ali's answer, you have to inject the IConfiguration object in constructor:

appsettings.js

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppSettings": {
      "ServerUrl": "some url"
  }
  
}

Define AppSettings class

    public class AppSettings
    {
        public string ServerUrl { get; set; }
    }

Startup.cs

 public class Startup
    {
        private readonly IConfiguration Configuration;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
        }
    }

Controller

    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly AppSettings config;

        public AuthenticationController (IOptions<AppSettings> config)
        {
            this.config= config.Value;
        }

        [HttpGet("token")]

        public ActionResult Token()
        {
          var server=config.ServerUrl;

        }

Works for .NET 5

Solution 24 - C#

For ASP.NET Core 6.0 you can simply:

appsetting.json

{
  "AppSettings": {
        "token": "1234"
    }
}

TestModel.cs

using Microsoft.Extensions.Configuration

public class TestModel : PageModel
{
    private readonly IConfiguration Configuration;

    public TestModel(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public ContentResult OnGet()
    {
        var myToken = Configuration["AppSettings:Token"];        
        return Content($"myToken value: {myToken}");
    }
}

Solution 25 - C#

With the latest iteration of netcoreapp 3.1 out, you can do this pretty simply without any third-party dependencies.

I created a gist for this, but you can use this class to read a JSON file and return dynamic properties.

using System.Text.Json;
using System.IO;

class ConfigurationLoader
{

    private dynamic configJsonData;
    public ConfigurationLoader Load(string configFilePath = "appsettings.json")
    {
        var appSettings = File.ReadAllText(configFilePath);
        this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object));
        return this;
    }

    public dynamic GetProperty(string key)
    {
        var properties = key.Split(".");
        dynamic property = this.configJsonData;
        foreach (var prop in properties)
        {
            property = property.GetProperty(prop);
        }

        return property;
    }
}

I specifically made this so I could use an appconfig.json in my dotnet console application. I just put this in my Program.Main function:

var config = new ConfigurationLoader();
config.Load();
Console.WriteLine(config.GetProperty("Environment.Name"));

And this will return a dynamic object for the property. (A JsonElement if it's not a primitive). My appsettings.json file looks like this:

{
  "Environment": {
    "Token": "abc-123",
    "Name": "Production"
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOluwafemiView Question on Stackoverflow
Solution 1 - C#Yuval ItzchakovView Answer on Stackoverflow
Solution 2 - C#hugView Answer on Stackoverflow
Solution 3 - C#Alexander S.View Answer on Stackoverflow
Solution 4 - C#MDMoore313View Answer on Stackoverflow
Solution 5 - C#tnJedView Answer on Stackoverflow
Solution 6 - C#kodebotView Answer on Stackoverflow
Solution 7 - C#Eric Milliot-MartinezView Answer on Stackoverflow
Solution 8 - C#OgglasView Answer on Stackoverflow
Solution 9 - C#Teoman shipahiView Answer on Stackoverflow
Solution 10 - C#AliView Answer on Stackoverflow
Solution 11 - C#Chris HalcrowView Answer on Stackoverflow
Solution 12 - C#Alper EbicogluView Answer on Stackoverflow
Solution 13 - C#NapalView Answer on Stackoverflow
Solution 14 - C#Tiago BarrosoView Answer on Stackoverflow
Solution 15 - C#GregoryView Answer on Stackoverflow
Solution 16 - C#MonolithcodeView Answer on Stackoverflow
Solution 17 - C#Alex HermanView Answer on Stackoverflow
Solution 18 - C#Lapenkov VladimirView Answer on Stackoverflow
Solution 19 - C#Hamed NaeemaeiView Answer on Stackoverflow
Solution 20 - C#CodeMonkeyView Answer on Stackoverflow
Solution 21 - C#Brian MooreView Answer on Stackoverflow
Solution 22 - C#jishan siddiqueView Answer on Stackoverflow
Solution 23 - C#The OneView Answer on Stackoverflow
Solution 24 - C#Juan Carlos IbarraView Answer on Stackoverflow
Solution 25 - C#Justin GilmanView Answer on Stackoverflow