ConfigurationOptionsValidator 1.0.4

dotnet add package ConfigurationOptionsValidator --version 1.0.4
                    
NuGet\Install-Package ConfigurationOptionsValidator -Version 1.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ConfigurationOptionsValidator" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ConfigurationOptionsValidator" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="ConfigurationOptionsValidator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ConfigurationOptionsValidator --version 1.0.4
                    
#r "nuget: ConfigurationOptionsValidator, 1.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ConfigurationOptionsValidator@1.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ConfigurationOptionsValidator&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=ConfigurationOptionsValidator&version=1.0.4
                    
Install as a Cake Tool

ConfigurationOptionsValidator

ConfigurationOptionsValidator is a powerful library for .NET that simplifies the process of validating configuration settings injected into your ASP.NET Core application using the Options pattern. This library ensures that your appsettings.json configurations are correctly set and that all required settings are present and valid.

ConfigurationOptionsValidator targets .NET 8 and ensures compatibility with the latest features and improvements in the .NET ecosystem.

With ConfigurationOptionsValidator, developers can validate their configurations easily, ensuring the application runs smoothly with the correct configuration values.

Note: The solution uses Serilog for logging configuration validation errors. Logs are stored in the specified logPath. If the logPath is not provided, a log file will be created by default in C:\TaskLogs.

ConfigurationOptionsValidator works seamlessly with the Options Pattern, which is a recommended approach for managing configuration in .NET. The Options pattern removes magic strings from your code, making it more readable and flexible. While it�s a great practice to use, even if you�re not using the Options pattern, this library can still help by validating your appsettings values and checking for any missing or incorrect properties.


New Changes in Version: 1.0.4

  • SerilogOptions: A new configuration class, SerilogOptions, has been added to allow developers to configure logging settings, including log levels and log file paths. If you want to use Serilog for logging configuration validation errors, you can easily configure it in your appsettings.json and inject it into your application.
  • BlazorErrorHandlingExtensions: A new method has been added to handle Blazor configuration errors more efficiently. Developers can now use a streamlined approach for managing missing configuration properties directly through the HandleBlazorConfigErrors method.


Features

  • Validates configuration settings injected using the Options pattern.
  • Ensures all required configurations are present and correctly set in appsettings.json.
  • Provides a simple and effective way to validate configuration types during application startup.
  • Supports validation for Blazor, API, and Console projects.
  • Includes security features to prevent exposing error details to external users.
  • Offers automatic and manual error handling options.
  • Added support for logging errors with Serilog through the SerilogOptions configuration.
  • New HandleBlazorConfigErrors method in BlazorErrorHandlingExtensions for easier configuration error handling in Blazor apps.
  • Improved error handling for missing configuration properties in Blazor applications.

Installation

Install the package via NuGet:

dotnet add package ConfigurationOptionsValidator --version 1.0.4

Setup

1. Register Services

In your Program.cs file, add the following to register the ConfigurationValidationManager service:

builder.Services.AddSingleton<ConfigurationValidationManager>();

Then, register the configuration settings by binding them to classes in your appsettings.json:

builder.Services.Configure<YourConfigOptions>(builder.Configuration.GetSection(nameof(YourConfigOptions)));

1.1 Configure Serilog (Optional)

The ConfigurationOptionsValidator includes a class called SerilogOptions for configuring logging with Serilog. If you'd like to use Serilog for logging, you can configure it as follows:

In your appsettings.json, add the following Serilog configuration:

"Serilog": {
  "MinimumLevel": {
    "Default": "Information",
    "Override": {
      "Microsoft": "Information",
      "System": "Information"
    }
  },
  "WriteTo": [
    {
      "Name": "File",
      "Args": {
        "path": "C:\\SeriLogs\\Client-.txt",
        "rollingInterval": "Day",
        "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}"
      }
    }
  ]
}

Then, in your Program.cs, inject the configuration into SerilogOptions:

builder.Services.Configure<SerilogOptions>(builder.Configuration.GetSection("Serilog"));


Usage Examples

2. Validate Configurations in Blazor

To validate your configurations in a Blazor application, retrieve the ConfigurationValidationManager from dependency injection and call the ValidateConfigurationTypes method:

var configValidator = app.Services.GetRequiredService<ConfigurationValidationManager>();

configValidator.ValidateConfigurationTypes(
    typeof(YourFirstConfigOptions),
    typeof(YourSecondConfigOptions),
    typeof(YourThirdConfigOptions)
);

var serilogOptions = app.Services.GetRequiredService<IOptions<SerilogOptions>>().Value;

2.1 Handle Configuration Errors

You can choose between two options to handle configuration errors in your Blazor application.

Option 1: Automatic Error Handling

This option uses the HandleBlazorConfigErrors method to automatically handle missing configuration properties and stop the app from running if there are any errors:

if (app.HandleBlazorConfigErrors(configValidator.MissingProperties,logPath: serilogOptions.WriteTo.FirstOrDefault()?.Args.Path))
{
  app.Run();
  return;
}

Option 2: Manual Error Handling

Alternatively, you can manually map an error page for missing configuration properties and stop the app from continuing to Razor components if errors are present:

app.MapBlazorConfigError(configValidator.MissingProperties,logPath:serilogOptions.WriteTo.FirstOrDefault()?.Args.Path);
if (configValidator.MissingProperties.Count > 0)
{
  app.Use(async (context, next) =>
  {
	if (!context.Request.Path.StartsWithSegments("/config-error"))
	{
	  context.Response.Redirect("/config-error");
	  return;
	}

	await next();
  });

  app.Run(); // stop app from continuing to Razor components etc.
  return;
}

3. Validate Configurations in API

In your API project, validate configurations by calling the ValidateApiConfiguration method:

if(!builder.ValidateApiConfiguration(logPath: logPath,
    typeof(YourFirstConfigOptions),
    typeof(YourSecondConfigOptions),
    typeof(YourThirdConfigOptions)))
{
    Environment.Exit(1);
}

3. Validate Configurations in a Console Application

In a .NET Console application, you can validate configurations as follows:

var services = new ServiceCollection();
var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

services.Configure<YourFirstConfigOptions>(config.GetSection(nameof(YourFirstConfigOptions)));
services.Configure<YourSecondConfigOptions>(config.GetSection(nameof(YourSecondConfigOptions)));
services.Configure<YourThirdConfigOptions>(config.GetSection(nameof(YourThirdConfigOptions)));

ConsoleConfigurationValidator.ValidateAndRunConsole(config, services,
    typeof(YourFirstConfigOptions),
    typeof(YourSecondConfigOptions), 
    typeof(YourThirdConfigOptions))


Error Handling and Security

For enhanced security, configure error handling to restrict access to error pages in production environments. You can add the following settings to your appsettings.json to prevent exposing errors to end users:

"ConfigurationErrorPageSettings": {
  "ForbiddenMessage": "Access to this page is restricted to authorized users only.",
  "SupportContact": {
    "Email": "support@company.com",
    "Phone": "+44 7890 123456",
    "Website": "https://support.company.com"
  }
}

This ensures that error messages are not displayed to the public, but are only available to the server hosting the application.


Why Use ConfigurationOptionsValidator?

With ConfigurationOptionsValidator, you no longer need to:

  • Manually check each configuration setting during application startup.
  • Expose sensitive configuration errors to end users.

ConfigurationOptionsValidator saves developers time and ensures a smoother, more reliable setup process for your ASP.NET Core applications.


Contributing

We welcome contributions! Please feel free to:


License

This project is licensed under the MIT License. See the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 182 4/10/2025
1.0.3 182 2/12/2025
1.0.2 183 2/11/2025 1.0.2 is deprecated.
1.0.1 169 2/11/2025 1.0.1 is deprecated.
1.0.0 166 2/11/2025 1.0.0 is deprecated because it has critical bugs.