Not sure what am I missing here but I am not able to get the values from my appsettings.json in my .net core application. I have my appsettings.json as:
{
"AppSettings": {
"Version": "One"
}
}
Startup:
public class Startup
{
private IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
}
public void ConfigureServices(IServiceCollection services)
{
//Here I setup to read appsettings
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
Model:
public class AppSettings
{
public string Version{ get; set; }
}
Controller:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings
is always null. Is there something that I am missing here?
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;
}
}
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();
}
...
}
There are many ways you can get the value you configure from the app settings:
ConfigurationBuilder.GetValue<T>
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": {
...
},
...
}
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);
}
}
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:
IOptions<T>
into the constructor of the controller/class you want to get values onYou 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; }
}
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);
...
}
...
}
}
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);
}
}