Aggiungere un file json
al vostro principale del progetto dir: config.json
{
"AppSettings": {
"TestKey" : "TestValue"
}
}
Creare un nuovo class
per config deserializzazione:
public class AppSettings
{
public string TestKey { get; set; }
}
In Startup.cs
:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
Ottenere le opzioni nel tuo controller
:
public HomeController(IOptions<AppSettings> settings)
{
var value = settings.Value.TestKey;
}
fonte
2015-12-14 17:49:22
Sotto 'References', ho aggiunto' System.Configuration (1.0.0) 'per DNX 4.5.1. Tuttavia, ottengo ancora "Il tipo o spazio dei nomi 'Configurazione' non esiste nello spazio dei nomi 'Sistema' (ti manca un assembly o un riferimento?)" –