Last active
September 28, 2023 08:32
-
-
Save yetanotherchris/9f3e75de1cfba0f3fae9a228794fdfc8 to your computer and use it in GitHub Desktop.
.NET Core Examples: configuration binding and appsetting.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Smtp": { | |
"Host": "smtp.gmail.com", | |
"Port": 587, | |
"UseSSL": true, | |
"Username": "bob", | |
"Password": "password", | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using Microsoft.Extensions.Configuration; | |
namespace Examples.Configuration | |
{ | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
// | |
// Nuget packages needed: | |
// - Microsoft.Extensions.Configuration | |
// - Microsoft.Extensions.Configuration.Abstractions | |
// - Microsoft.Extensions.Configuration.Binder | |
// - Microsoft.Extensions.Configuration.Json | |
// | |
// Make sure appsettings.json has its properties set to "content", "always copy" | |
// | |
var builder = new ConfigurationBuilder(); | |
builder | |
.SetBasePath(Directory.GetCurrentDirectory()) | |
.AddJsonFile("appsettings.json", false); | |
IConfigurationRoot configuration = builder.Build(); | |
var smtpConfiguration = new SmtpConfiguration(); | |
IConfigurationSection section = configuration.GetSection("Smtp"); | |
section.Bind(smtpConfiguration); | |
Console.WriteLine(smtpConfiguration.Host); | |
Console.Read(); | |
} | |
} | |
public class SmtpConfiguration | |
{ | |
public string Host { get; set; } | |
public int Port { get; set; } | |
public string Username { get; set; } | |
public string Password { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment