How to Read Appsettings Values from a .Json File in ASP.NET Core

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

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"));
}
}

Reading appsetting-test.json file in asp.net core 5 test project

If you want user details as an object, you can have a class created and bind it to user section from your configuration.

Something like,

private IConfiguration _iAppSettingConfiguration;
private static string _readonlypageUrl;
public GivenAccount(PlaywrightFixture playwrightFixture)
{
_iAppSettingConfiguration = IAppSettingConfiguration.InitConfiguration();
_readonlypageUrl = _iAppSettingConfiguration["baseUrl"];

var _user = new UserDetail();
_iAppSettingConfiguration.GetSection(UserDetail.User).Bind(_user);

}

public class UserDetail
{
public const string User = "user";

public string UserName { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
}

Read appsettings.{env}.json objects in .NET 6 API - Values coming as NULL

I think you might need to use configuration.GetSection in Services.Configure which means registering Config object from Config section of appsettings.json.

builder.Services.Configure<Config>(configuration.GetSection("Config"));

How to get values from appsettings.json in a console application using .NET Core?

Your example is mixing in some ASP NET Core approaches that expect your code to be hosted. To minimally solve the issue of getting options or settings from a JSON configuration, consider the following:

A config.json file, set to "Copy to Output Directory" so that it is included with the build:

{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}

The following approach will load the content from the JSON file, then bind the content to two strongly-typed options/settings classes, which can be a lot cleaner than going value-by-value:

using System;
using System.IO;
using Microsoft.Extensions.Configuration;

// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json

namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false);

IConfiguration config = builder.Build();

var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
}
}

public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}

public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
}

Get values from appsettings.json in .net core 3.1

In your appsettings.json myKey is inside an AppSettings object.

That whole object is being loaded, so you'll need to reference it:

var myValue = config["AppSettings:myKey"];

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

Show appsettings.json value in cshtml file in .NET Core

Here is a demo to show value from appsettings.json in view:

appsettings.json:

{
...
"Test": {
"TestValue": "testValue"

}
}

view:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
@Configuration.GetSection("Test")["TestValue"]

How to use appsettings.json in Asp.net core 6 Program.cs file

While the examples above work, the way to do this is the following:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["Redis"];
});

The WebApplicationBuilder has a configuration object as a property that you can use.

Getting value from appsettings.json in .net core


Program and Startup class

.NET Core 2.x

You don't need to new IConfiguration in the Startup constructor. Its implementation will be injected by the DI system.

// Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}

// Startup.cs
public class Startup
{
public IHostingEnvironment HostingEnvironment { get; private set; }
public IConfiguration Configuration { get; private set; }

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
this.HostingEnvironment = env;
this.Configuration = configuration;
}
}

.NET Core 1.x

You need to tell Startup to load the appsettings files.

// Program.cs
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();

host.Run();
}
}

//Startup.cs
public class Startup
{
public IConfigurationRoot Configuration { get; private set; }

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();

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


Getting Values

There are many ways you can get the value you configure from the app settings:

  • Simple way using ConfigurationBuilder.GetValue<T>
  • Using Options Pattern

Let's say your appsettings.json looks like this:

{
"ConnectionStrings": {
...
},
"AppIdentitySettings": {
"User": {
"RequireUniqueEmail": true
},
"Password": {
"RequiredLength": 6,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true,
"RequireNonAlphanumeric": true
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpanInMins": 30,
"MaxFailedAccessAttempts": 5
}
},
"Recaptcha": {
...
},
...
}

Simple Way

You can inject the whole configuration into the constructor of your controller/class (via IConfiguration) and get the value you want with a specified key:

public class AccountController : Controller
{
private readonly IConfiguration _config;

public AccountController(IConfiguration config)
{
_config = config;
}

[AllowAnonymous]
public IActionResult ResetPassword(int userId, string code)
{
var vm = new ResetPasswordViewModel
{
PasswordRequiredLength = _config.GetValue<int>(
"AppIdentitySettings:Password:RequiredLength"),
RequireUppercase = _config.GetValue<bool>(
"AppIdentitySettings:Password:RequireUppercase")
};

return View(vm);
}
}

Options Pattern

The ConfigurationBuilder.GetValue<T> works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.

To use options pattern:

  1. Define classes to represent the structure
  2. Register the configuration instance which those classes bind against
  3. Inject IOptions<T> into the constructor of the controller/class you want to get values on

1. Define configuration classes to represent the structure

You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:

public class AppIdentitySettings
{
public UserSettings User { get; set; }
public PasswordSettings Password { get; set; }
public LockoutSettings Lockout { get; set; }
}

public class UserSettings
{
public bool RequireUniqueEmail { get; set; }
}

public class PasswordSettings
{
public int RequiredLength { get; set; }
public bool RequireLowercase { get; set; }
public bool RequireUppercase { get; set; }
public bool RequireDigit { get; set; }
public bool RequireNonAlphanumeric { get; set; }
}

public class LockoutSettings
{
public bool AllowedForNewUsers { get; set; }
public int DefaultLockoutTimeSpanInMins { get; set; }
public int MaxFailedAccessAttempts { get; set; }
}

2. Register the configuration instance

And then you need to register this configuration instance in ConfigureServices() in the start up:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
...

namespace DL.SO.UI.Web
{
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
...
var identitySettingsSection =
_configuration.GetSection("AppIdentitySettings");
services.Configure<AppIdentitySettings>(identitySettingsSection);
...
}
...
}
}

3. Inject IOptions

Lastly on the controller/class you want to get the values, you need to inject IOptions<AppIdentitySettings> through constructor:

public class AccountController : Controller
{
private readonly AppIdentitySettings _appIdentitySettings;

public AccountController(IOptions<AppIdentitySettings> appIdentitySettingsAccessor)
{
_appIdentitySettings = appIdentitySettingsAccessor.Value;
}

[AllowAnonymous]
public IActionResult ResetPassword(int userId, string code)
{
var vm = new ResetPasswordViewModel
{
PasswordRequiredLength = _appIdentitySettings.Password.RequiredLength,
RequireUppercase = _appIdentitySettings.Password.RequireUppercase
};

return View(vm);
}
}


Related Topics



Leave a reply



Submit