< .Net Core

Konfiguráció

Szerző: Sallai András

Copyright © 2024, Sallai András

Szerkesztve: 2024

Licenc: CC BY-SA 4.0

Web: https://szit.hu

Függőség telepítése

dotnet add package Microsoft.Extensions.Configuration.Json

dotnet add package Microsoft.Extensions.Configuration.Binder

Konfig

{ "egy": "kettő" }

Beolvasás

using Microsoft.Extensions.Configuration; var builder = new ConfigurationBuilder(); builder .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false); var conf = builder.Build(); var a = conf.GetValue<string>("egy"); Console.WriteLine(a); Console.Read();

Felhasználók

{ "user": "janos", "pass": "titok" }
using Microsoft.Extensions.Configuration; var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json", false); var conf = builder.Build(); var user = conf.GetValue<string>("user"); var pass = conf.GetValue<string>("pass"); Console.WriteLine(user + ":" + pass);

Objektum

{ "database": { "user": "janos", "pass": "titok" } }
using Microsoft.Extensions.Configuration; var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json", false); var conf = builder.Build(); var user = conf.GetValue<string>("database:user"); var pass = conf.GetValue<string>("database:pass"); Console.WriteLine(user + ":" + pass);

Objektum másként

{ "database": { "user": "janos", "pass": "titok" } }
using Microsoft.Extensions.Configuration; var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json", false); var conf = builder.Build(); var user = conf.GetSection("database").GetValue<string>("user"); var pass = conf.GetSection("database").GetValue<string>("pass"); Console.WriteLine(user + ":" + pass);

Láncolva egyszerűbben

{ "database": { "user": "janos", "pass": "titok" } }
using Microsoft.Extensions.Configuration; var conf = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json") .Build(); var user = conf["database:user"]; var pass = conf["database:pass"]; Console.WriteLine(user + ":" + pass);