.NET by Doug

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:

Comments