Introduction
Learn how to use ValidateOnStart to assert that required directories exist using a class project that may be used in multiple projects for consistency, rather than rewriting the same code over and over again.
Demonstration
Step 1
First, add the class project with validation classes to the front-end project.
Next, add a section in the front-end project’s appsetting.json file pointing to the files containing the help desk phone number and email address.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"FileSettings": {
"SecretsDirectory": "C:\\Secrets"
}
}
The value for FileSettings.SecretsDirectory needs to point to the folder containing, in this case, phone and email files supplied in the project HelpDeskApplication in the Secrets folder.
Step 2
Add a project reference for SpecialValidatorsLibrary class project. For your projects create a local NuGet package for SpecialValidatorsLibrary.
Step 3
Add the following code to Program.cs
// Bind configuration section to FileSettings
builder.Services.AddOptions<RequiredDirectories>()
.Bind(builder.Configuration.GetSection(nameof(FileSettings)));
// using IValidateOptions<T>:
builder.Services.AddSingleton<IValidateOptions<RequiredDirectories>, DirectoryOptionsValidation>();
builder.Services.AddOptions<RequiredDirectories>()
.ValidateOnStart();
var fileSettings = builder.Configuration.GetSection(nameof(FileSettings)).Get<FileSettings>();
// Define the path where key-per-file secrets are stored
var secretsPath = fileSettings?.SecretsDirectory;
if (Directory.Exists(secretsPath))
{
builder.Configuration.AddKeyPerFile(secretsPath, optional: true, reloadOnChange: true);
builder.Services.Configure<HelpDesk>(builder.Configuration);
}
Step 4
_Layout.cshtml, add the following at top of page.
@using SpecialValidatorsLibrary.Models
@using Microsoft.Extensions.Options
@inject IOptions<HelpDesk> HelpDeskOptions
Next replace footer element with.
<footer class="border-top footer text-muted">
<div class="container">
<span class="text-success fw-bold">Help Desk:</span>
<span>Help Desk: <strong>Phone</strong> @HelpDeskOptions.Value.Phone</span><div class="vr opacity-100 ms-2"></div> <span><strong>Email</strong> <a href="mailto:@HelpDeskOptions.Value.Email">@HelpDeskOptions.Value.Email</a></span>
</div>
</footer>
Step 5
Run the front-end project and note the footer contains the phone and email address.
Summary
Although only one folder was used for reading values, other uses, such as validating specific folders, exist, e.g., for downloading files.
Top comments (0)