I stumbled across an issue when using the Options pattern where model properties are being set to null when bound to an empty JSON array.
appsettings.json:
{
"MyOptions": {
"Values": []
}
}
MyOptions.cs:
public sealed class MyOptions
{
public IEnumerable<string> Values { get; set; }
}
Startup.cs:
...
services.Configure<MyOptions>(
_configuration.GetSection(nameof(MyOptions));
...
The above configuration successfully builds and injects an IOptions<MyOptions> when required, however Values property is set to null rather than an empty enumerable. This would cause the following code to throw a NullReferenceException:
public class MyService
{
public MyService(IOptions<MyOptions> options)
{
var values = options.Value.Values;
foreach (var val in values)
{
// Do something
}
}
}
This has been raised as an issue on the dotnet repo (https://github.com/dotnet/extensions/issues/1341) although MS seem to have closed it as "working as designed".
Is there a workaround to prevent the NullReferenceException being thrown?