访问应用设置触发System.ArgumentNullException错误,求排查原因
System.ArgumentNullException异常解析
异常信息
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 's')
at System.ArgumentNullException.Throw(String paramName)
at System.Text.Encoding.GetBytes(String s)
at Program.$(String[] args) in C:\Users\ramit\OneDrive\Documents\GitHub\Photos\HSPA2024\WebAPI\Program.cs:line 24
相关代码
Program.cs 第23-24行
var secretKey = builder.Configuration.GetSection("AppSettings:Key").Value; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
appsettings配置
"AppSettings": { "Key": "this is my top secret, try to add more for it to work correctly" }
问题解答
1. 错误表示什么?
该错误说明调用方法时传入了null值,但目标方法要求对应参数必须为非空值,因此触发参数为空的异常。
2. (Parameter 's')指的是什么?
从调用栈可以看到,异常来自System.Text.Encoding.GetBytes(String s)方法,这里的's'就是该方法的输入参数。对应你的代码第24行,你传入了secretKey作为GetBytes的参数,说明此时secretKey的值是null,才触发了这个异常。
为什么secretKey会是null?
尽管你在appsettings中配置了AppSettings:Key,但可能存在以下情况:
- 程序运行时加载的不是你当前编辑的appsettings文件(比如生产环境默认加载
appsettings.Production.json,而该文件未配置此项) - 配置文件的JSON格式存在语法错误(比如引号不匹配、逗号遗漏),导致配置读取失败
- 使用
GetSection("AppSettings:Key").Value的读取方式在某些场景下无法正确获取值
解决建议
- 确认程序启动时加载的是正确的配置文件
- 检查appsettings的JSON格式是否完全正确
- 修改配置读取代码并添加空值校验:
var secretKey = builder.Configuration["AppSettings:Key"]; if (string.IsNullOrWhiteSpace(secretKey)) { throw new InvalidOperationException("未找到有效的AppSettings:Key配置项"); } var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
内容的提问来源于stack exchange,提问作者taleen wahdan
相关产品推荐
相关产品推荐

