Introduction
In this article, we are going to learn how to validate appsetting configuration values.
Generally, we store the application configuration in setting and reading those values through IConfiguration, and Option pattern, but sometimes there is are possibility of having this configuration error prone like.
- Forgot to add settings values
- Incorrect section name while reading the value
- Data type mismatch
- Typo error in property name
If anything above happens, the application won't throw an error at the application start, and the application can behave differently at runtime or throw an exception at runtime.
How to resolve this issue?
We have 3 ways to validate this.
- We can use the Data Annotation to validate the configuration class.
- Options Validation using Delegates.
- We can integrate FluentValidation using the IValidationOptions interface.
First, we will see how to Add the Data Annotation to validate and read the setting configuration.
"Smtp": {
"Server": "mail.whatever.com",
"Port1": "25",
"FromAddress": "[email protected]"
}
ConfigurationModel
public class SmtpOptions
{
[Required(AllowEmptyStrings =false)]
public string Server { get; set; }
[Required(AllowEmptyStrings = false)]
public string Port { get; set; }
[Required(AllowEmptyStrings = false)]
public string FromAddress { get; set; }
}
Add the code below to the Program.cs.
services.AddOptions<SmtpOptions>()
.BindConfiguration("Smtp") // Bind the smtp section in config
.ValidateDataAnnotations() //Enable the validation
.ValidateOnStart(); //Validate on app start
To Read the value, inject the IOption<SmtpOption> in the Controller as shown below.
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly SmtpOptions _smtp;
public EmployeeController(IOptions<SmtpOptions> smtp)
{
_smtp = smtp.Value;
}
[HttpGet]
public IActionResult GetEmployee()
{
return Ok();
}
}
Now try to run the application, and when this Employee Controller hits, we can see we are able to read and validate the app settings; at this time, our configuration is valid, so it won't throw any exception.

Now let's change the configuration intentionally, from Port to Port1, to see whether validation is happening or not.





Join the conversation! Your thoughts help the community grow.