Configuration in .NET
This code snippet demonstrates configuring and retrieving custom settings from appsettings.json
. It defines a ClientSettings class to manage client-specific configurations such as name and URL. The appsettings.json
file is structured to hold these settings under a "Clients
" section. The code includes validation checks to ensure that the required settings are provided and the URL is valid.
// Configuration in appsettings.json
{
"Clients": {
"Client": {
"Name": "Acme Corporation",
"Url": "https://acme.example.com"
}
}
}
// Settings class
internal class ClientSettings
{
public const string ConfigSection = "Clients.Client";
public string ClientName { get; set; } = "DefaultClientName";
public string ClientUrl { get; set; } = string.Empty;
public static ClientSettings Load(IConfiguration configuration)
{
ClientSettings settings = configuration.GetSection(ConfigSection).Get<ClientSettings>() ?? throw new ConfigurationErrorsException($"'{ConfigSection}' section not found. Add configuration to appsettings.json");
if (string.IsNullOrWhiteSpace(settings.ClientName)) throw new ConfigurationErrorsException("ClientName is null or empty");
if (string.IsNullOrWhiteSpace(settings.ClientUrl)) throw new ConfigurationErrorsException("ClientUrl is null or empty");
if (!(Uri.TryCreate(settings.ClientUrl, UriKind.Absolute, out Uri? uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)))
{
throw new ConfigurationErrorsException("ClientUrl is not a valid URL");
}
return settings;
}
}
// Using setting
public Client(IConfiguration configuration)
{
_clientSettings = ClientSettings.Load(configuration);
}
Links and Explanation:
-
Makolyte - C# How to Read Custom Configuration from appsettings.json: This link provides a detailed guide on reading custom configurations from
appsettings.json
in C#. -
Stack Overflow - Configuration.GetSection easily gets primitive string values but not complex values: This Stack Overflow thread discusses issues related to retrieving complex values using
Configuration.GetSection
in .NET applications and provides insights into resolving such problems.
Comments(1)
Mike Sheldon
3/19/2024 2:32:01 AM