Ik weet niet zeker wat ik hier mis, maar ik ben niet in staat om de waarden van mijn appsettings.json in mijn .net core applicatie te krijgen. Ik heb mijn appsettings.json als:
{
"AppSettings": {
"Version": "One"
}
}
Opstarten:
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 altijd null. Is er iets dat ik hier over het hoofd zie?
Bedankt @Kirk voor het erop wijzen dat ik er niet van uit moet gaan'dat het .NET Core 2.0 is!
Je hoeft IConfiguration
niet nieuw te maken in de Startup
constructor. Zijn implementatie zal worden geïnjecteerd door het DI systeem.
// Programma.cs
openbare klasse Programma
{
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 Opstarten
{
public IHostingEnvironment HostingEnvironment { get; private set; }
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
deze.HostingEnvironment = env;
this.Configuration = configuration;
}
}
Je moet Startup
vertellen om de app-instellingen bestanden te laden.
// Programma.cs
public class Programma
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
//Startup.cs
publieke klasse Startup
{
public IConfigurationRoot Configuration { get; private set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optioneel: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optioneel: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
...
}
Er zijn vele manieren om de waarde te krijgen die je configureert uit de app settings:
ConfigurationBuilder.GetValue<T>
appsettings.json
er als volgt uitziet:{
"ConnectionStrings": {
...
},
"AppIdentitySettings": {
"User": {
"RequireUniqueEmail": true
},
"Password": {
"RequiredLength": 6,
"RequireLowercase": true,
"RequireUppercase": true,
"RequireDigit": true,
"RequireNonAlphanumeric": true
},
"Lockout": {
"AllowedForNewUsers": true,
"DefaultLockoutTimeSpanInMins": 30,
"MaxFailedAccessAttempts": 5
}
},
"Recaptcha": {
...
},
...
}
Je kunt de hele configuratie in de constructor van je controller/klasse injecteren (via IConfiguration
) en de waarde ophalen die je wilt met een gespecificeerde sleutel:
``csharp
public class AccountController : Controller
{
private readonly IConfiguration _config;
public AccountController(IConfiguration config)
{
_config = config;
}
[AllowAnonymous]
public IActionResult ResetPassword(int userId, string code)
{
var vm = nieuw ResetPasswordViewModel
{
PasswordRequiredLength = _config.GetValue
## Opties Patroon ##
De `ConfigurationBuilder.GetValue<T>` werkt prima als je maar een of twee waarden uit de app instellingen nodig hebt. Maar als je meerdere waarden uit de app instellingen wilt halen, of je wilt die key strings niet op meerdere plaatsen hard coderen, dan is het misschien makkelijker om het *Options Pattern* te gebruiken. Het opties patroon gebruikt klassen om de hiërarchie/structuur weer te geven.
Om opties patroon te gebruiken:
IOptions<T>
in de constructor van de controller/klasse waar je waarden op wilt krijgenU kunt klassen definiëren met eigenschappen die precies moeten overeenkomen met de sleutels in uw app-instellingen. De naam van de klasse hoeft niet overeen te komen met de naam van de sectie in de app instellingen:
public class AppIdentitySettings
{
public UserSettings User { get; set; }
public PasswordSettings Password { get; set; }
public LockoutSettings Lockout { get; set; }
}
publieke klasse UserSettings
{
public bool RequireUniqueEmail { get; set; }
}
publieke klasse 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; } }
}
publieke klasse LockoutSettings
{
public bool AllowedForNewUsers { get; set; }
public intaultLockoutTimeSpanInMins { get; set; }
public int MaxFailedAccessAttempts { get; set; }
}
En dan moet je deze configuratie instantie registreren in ConfigureServices()
in de opstart:
met behulp van Microsoft.Extensions.Configuration;
met behulp van Microsoft.Extensions.DependencyInjection;
...
namespace DL.SO.UI.Web
{
publieke klasse Opstarten
{
...
public void ConfigureServices(IServiceCollection services)
{
...
var identitySettingsSection =
_configuration.GetSection("AppIdentitySettings");
services.Configure<AppIdentitySettings>(identitySettingsSection);
...
}
...
}
}
Als laatste op de controller/klasse waar je de waarden wilt krijgen, moet je IOptions<AppIdentitySettings>
injecteren via de constructor:
``csharp
public class AccountController : Controller
{
private readonly AppIdentitySettings _appIdentitySettings;
public AccountController(IOptions
Aanvulling op het antwoord van David Liang's voor Core 2.0 -
appsettings.json
bestand's zijn gekoppeld aan ASPNETCORE_ENVIRONMENT
variabele.
ASPNETCORE_ENVIRONMENT
kan op elke waarde worden ingesteld, maar drie waarden worden door het framework ondersteund: Ontwikkeling
, Staging
, en Productie
. Als ASPNETCORE_ENVIRONMENT
niet is ingesteld, zal het standaard op Production
staan.
Voor deze drie waarden worden deze appsettings.ASPNETCORE_ENVIRONMENT.json bestanden out of the box ondersteund - appsettings.Staging.json
, appsettings.Development.json
en appsettings.Production.json
De bovenstaande drie applicatie-instellingen json-bestanden kunnen worden gebruikt om meerdere omgevingen te configureren.
Voorbeeld - appsettings.Staging.json
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"System": "Information",
"Microsoft": "Information"
}
},
"MyConfig": "My Config Value for staging."
}
Gebruik Configuration["config_var"]
om een configuratiewaarde op te halen.
public class Startup
{
public Startup(IHostingEnvironment env, IConfiguration config)
{
Environment = env;
Configuration = config;
var myconfig = Configuration["MyConfig"];
}
public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }
}
Maak gewoon een AnyName.cs bestand en plak de volgende code.
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Custom
{
static class ConfigurationManager
{
public static IConfiguration AppSetting { get; }
static ConfigurationManager()
{
AppSetting = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("YouAppSettingFile.json")
.Build();
}
}
}
Vervang YouAppSettingFile.json bestandsnaam met uw bestandsnaam.
Uw .json bestand zou er uit moeten zien zoals hieronder.
{
"GrandParent_Key" : {
"Parent_Key" : {
"Child_Key" : "value1"
}
},
"Parent_Key" : {
"Child_Key" : "value2"
},
"Child_Key" : "value3"
}
Nu kun je het gebruiken.
Vergeet niet Verwijzing toe te voegen in je klasse waar je het wilt gebruiken.
using Custom;
Code om waarde op te halen.
string value1 = ConfigurationManager.AppSetting["GrandParent_Key:Parent_Key:Child_Key"];
string value2 = ConfigurationManager.AppSetting["Parent_Key:Child_Key"];
string value3 = ConfigurationManager.AppSetting["Child_Key"];