oktatas:programozas:csharp:dotnetcore:konfiguracio
Tartalomjegyzék
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
- appsettings.json
{ "egy": "kettő" }
Beolvasás
- Program.cs
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
- appsettings.json
{ "user": "janos", "pass": "titok" }
- Program.cs
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
- appsettings.json
{ "database": { "user": "janos", "pass": "titok" } }
- Program.cs
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
- appsettings.json
{ "database": { "user": "janos", "pass": "titok" } }
- Program.cs
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
- config.json
{ "database": { "user": "janos", "pass": "titok" } }
- Program.cs
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);
oktatas/programozas/csharp/dotnetcore/konfiguracio.txt · Utolsó módosítás: 2024/02/22 21:17 szerkesztette: admin