I have a .net 8 web application. In the Program.cs I have the following code:
var applicationName = builder.Configuration.GetValue<string>("DataProtection:ApplicationName");
builder.Services.AddDataProtection().SetApplicationName(applicationName);
How can this code be re-written so applicationName
becomes validated in a correct way. The only rule is that it should not be null or empty.
I have seen that .net 8 has some new stuff for validating options and configurations. How could that be applied in this scenario?
You can use ValidateDataAnnotations
documentation
Example define poco as you needed
public class DataProtectionOptions
{
[Required(ErrorMessage = "The ApplicationName for data protection is required.")]
public string ApplicationName { get; set; }
}
Bind and validate configuration
builder.Services.AddOptions<DataProtectionOptions>()
.Bind(builder.Configuration.GetSection("DataProtection"))
.ValidateDataAnnotations();