Because your appsettings.json file holds an item with key "myKey", the specified conversion to int will always get executed regardless of whether the corresponding value is a valid int or is null or is an empty string. This conversion will obviously fail for those last 2.
Only converting to int? won't be enough since the null value found will not trigger the provided default value being applied, because the default value for int? is null.
A possible solution to deal with all scenarios where the item in appsettings.json is missing or holds a null value or holds a empty string value is below one, which doesn't provide a default value to the GetValue method, but relies on the null-coalescing operator.
var settingValue = configuration.GetValue<int?>("myKey") ?? HardCodedDefault;
appsettings.json
{
"myKey": null
}
Alternatively, you can just put that setting as a comment in your appsettings.json file, which represents the missing key scenario, returning the default value passed to GetValue.
{
// "myKey": null
}