You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在appsettings.json保留int配置键并使用默认值?

解决int类型配置项读取时null/空字符串抛出异常的问题

你在appsettings.json中保留myKey配置键,希望仅在需要时指定int值,否则回退到硬编码默认值,但当配置值设为null或空字符串时,原代码会抛出转换异常:

无法将配置项'myKey'的值转换为类型'System.Int32'

原代码:

const int HardCodedDefault = 42;
int settingValue = configuration.GetValue<int>("myKey", HardCodedDefault);

两种可行的解决方法:

  • 方法一:先校验配置值有效性再解析
    通过GetSection获取配置项,先判断值是否非空且能成功解析为int,再赋值,否则用默认值:
const int HardCodedDefault = 42;
var settingSection = configuration.GetSection("myKey");
int settingValue = HardCodedDefault;

if (!string.IsNullOrEmpty(settingSection.Value) && int.TryParse(settingSection.Value, out var parsedValue))
{
    settingValue = parsedValue;
}
  • 方法二:用可空int作为中间类型读取
    利用GetValue<int?>处理null/空字符串的情况(此时会返回null),再通过空合并运算符回退到默认值:
const int HardCodedDefault = 42;
int? tempValue = configuration.GetValue<int?>("myKey");
int settingValue = tempValue ?? HardCodedDefault;

原理说明

原代码中GetValue<int>会强制尝试将配置值转换为int类型,当值为null或空字符串时,转换逻辑直接抛出异常;而GetValue<int?>对无效值会返回null,不会触发异常,后续通过空合并运算符即可安全回退到默认值。

内容的提问来源于stack exchange,提问作者Medinoc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:09:52