You need to set that up in your Startup
configuration
public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public void ConfigureServices(IServiceCollection services)
{
var value = _config["key"];
}
public void Configure(IApplicationBuilder app, IConfiguration config)
{
var value = config["key"];
}
}
MS Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2#access-configuration-during-startup
Separation of Concerns
If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings
files and injecting them into your configuration classes within projects.
It has 2 extensions you can use:
public static T Get<T>(this IConfiguration configuration);
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
IConfiguration config) where TOptions : class;
Example:
I put all security related services using Microsoft.AspNetCore.Identity
into its own project called DL.SO.Services.Security
.
Security settings in appsettings.json
I define configurations, called "AppIdentitySettings", for identity options I want to set up in ASP.NET Core Identity
framework in my web/start-up project.
{
"ConnectionStrings": {
...
},
"AppIdentitySettings": {
"User": {
"RequireUniqueEmail": true
},
"Password": {
"RequiredLength": 6,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true,
"RequireNonAlphanumeric": true
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpanInMins": 30,
"MaxFailedAccessAttempts": 5
}
},
"Recaptcha": {
...
},
...
}
Configuration classes
Then you need to define configuration classes, which are just POCOs, to represent your configuration structure in appsettings.json
. The name of the configuration class doesn't have to match the section name you define in the appsettings.json
, but rather the names of the properties need to match.
namespace DL.SO.Services.Security
{
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; }
}
}
Above is from and in more detail: https://stackoverflow.com/a/46940811/2343826