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

.NET Core 6 Web API迁移后无法读取appsettings.json配置值的问题排查与解决

.NET 6迁移中读取appsettings.json空引用问题的解决

我最近在把项目从.NET Core 5.0迁移到.NET 6.0时,遇到了一个让人头疼的配置读取问题,折腾了好一阵才找到根源,分享出来给有同样困扰的朋友参考。

问题描述

在.NET Core 5.0项目中,我原本是这样配置DbContext的:

// database context
services.AddDbContext<QuoteCMSContext>(options => options.UseSqlite(Configuration["SqliteConnectionString"]));

迁移到.NET 6.0后,我按照新的启动模式改成用builder来配置,先后尝试了两种写法:

// 写法1
builder.Services.AddDbContext<QuoteCMSContext>(options => options.UseSqlite(builder.Configuration["SQLiteConnectionString"]));

// 写法2
builder.Services.AddDbContext<QuoteCMSContext>(options => options.UseSqlite(builder.Configuration.GetConnectionString("SQLiteConnectionString")));

结果两种写法都抛出了空引用异常。一开始我以为是配置键名或者读取方式的问题,还特意检查了我的appsettings.json(内容如下),确认键名完全匹配:

{ 
  "Logging": { 
    "LogLevel": { 
      "Default": "Information", 
      "Microsoft.AspNetCore": "Warning" 
    } 
  }, 
  "AllowedHosts": "*", 
  "SQLiteConnectionString": "Data Source=quotesdatabase.db", 
  "AzureSqlServerConnectionString": "Server=tcp:.database.windows.net,1433;Initial Catalog=DBName;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;", 
  "CorsOriginLocalHost": "http://localhost:3000", 
  "CorsOriginStaging": "https://randomstuffreactjsappzeropoint4.azurewebsites.net", 
  "CorsOriginProduction": "https://randomstuffreactjsappzeropoint4.azurewebsites.net", 
  "ConnectionStrings": { 
    "SQLiteConnectionString": "Data Source=quotesdatabase.db" 
  } 
}

更奇怪的是,后来配置CORS的时候,读取Origin配置也出现了同样的空引用异常:

builder.Services.AddCors(cors => { 
  cors.AddDefaultPolicy( 
    policy => { 
      policy.WithOrigins(builder.Configuration["CorsOriginLocalHost"], builder.Configuration["CorsOriginStaging"], builder.Configuration["CorsOriginProduction"]); 
      policy.AllowAnyMethod(); 
      policy.AllowAnyHeader(); 
      policy.AllowCredentials(); 
    } 
  ); 
});

这时候我才意识到,问题根本不是读取语法的问题,而是程序根本没找到并加载appsettings.json文件。

问题根源&解决方案

经过一番排查,我发现了问题所在:之前调试SQLite的时候,我手动修改了项目的工作目录,导致程序一直在错误的路径下查找appsettings.json。

虽然在.NET Core 5.0中我需要手动设置工作目录,但.NET 6.0的默认启动逻辑已经不需要这个操作了。我回到项目属性中,清空了自定义设置的工作目录路径,重新运行项目后,所有配置值都能正常读取了,DbContext和CORS的配置也都正常工作了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:42:29