运行代码时遭遇System.ArgumentNullException错误求助
问题分析与解决方案
异常根源
你遇到的System.ArgumentNullException(参数s未实例化),本质是调用Encoding.UTF8.GetBytes(s)时,传入的s为null——也就是jwtConfig["Jwt:SecretKey"]没有从配置文件中读取到有效值,大概率是配置加载失败或配置格式错误导致的。
具体解决步骤
1. 修正appsettings.json格式错误
你的配置文件中Jwt节点最后一项"ExpirationInMinutes": 60后面多了一个逗号,这会导致JSON解析失败,配置无法正常加载。修正后的完整配置:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "ConnectionStrings": { "DefaultConnection": "Server=.\\sqlexpress;Database=InvoiceAppDB;Trusted_Connection=True" }, "AllowedHosts": "*", "Jwt": { "Issuer": "https://localhost:7063/", "Audience": "https://localhost:7063/", "SecretKey": "your_secret_key", "ExpirationInMinutes": 60 } }
2. 确保配置正确绑定
不要直接用未初始化的jwtConfig对象读取配置,改用IConfiguration的官方绑定方式,推荐使用强类型配置类(更安全易维护):
步骤1:定义JWT配置类
public class JwtSettings { public string Issuer { get; set; } public string Audience { get; set; } public string SecretKey { get; set; } public int ExpirationInMinutes { get; set; } }
步骤2:绑定并验证配置
在Program.cs中替换原有的认证配置代码:
// 从配置文件绑定JWT设置 var jwtSettings = builder.Configuration.GetSection("Jwt").Get<JwtSettings>(); // 提前验证关键配置是否存在,避免后续异常 if (string.IsNullOrEmpty(jwtSettings.SecretKey)) { throw new InvalidOperationException("请在appsettings.json中配置有效的Jwt:SecretKey"); } // 配置JWT认证 builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtSettings.Issuer, ValidAudience = jwtSettings.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)) }; });
3. 调试验证配置加载
如果仍有问题,可以在绑定后添加调试输出,确认配置是否正确读取:
Console.WriteLine($"Jwt Issuer: {jwtSettings.Issuer}"); Console.WriteLine($"Jwt SecretKey: {jwtSettings.SecretKey}");
内容的提问来源于stack exchange,提问作者Olorunfemi Philip Ayanfe
相关产品推荐
相关产品推荐

