.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 (1)

Mike Sheldon

3/19/2024 2:32:01 AM
Hi there, My name is Mike from Monkey Digital, Allow me to present to you a lifetime revenue opportunity of 35% That's right, you can earn 35% of every order made by your affiliate for life. Simply register with us, generate your affiliate links, and incorporate them on your website, and you are done. It takes only 5 minutes to set up everything, and the payouts are sent each month. Click here to enroll with us today: https://www.monkeydigital.org/affiliate-dashboard/ Think about it, Every website owner requires the use of search engine optimization (SEO) for their website. This endeavor holds significant potential for both parties involved. Thanks and regards Mike Sheldon Monkey Digital