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

ASP.NET Core用ConfigurationManager读取appsettings连接串返回null如何解决

错误原因

  • 第一:System.Configuration.ConfigurationManager 是 .NET Framework 时代用于读取 app.config/web.config 配置文件的类,默认不会读取 ASP.NET Core 项目的 appsettings.json 文件,因此你用它获取连接串自然返回 null。
  • 第二:你在控制器中手动通过 new LibraryStoreContext() 创建上下文实例,没有使用 Startup 中注入的已配置好的 DbContext,此时 OnConfiguring 方法中的 optionsBuilder.IsConfigured 为 false,会执行你写的错误配置逻辑,触发报错。

修复步骤

步骤1:修正 DbContext 的 OnConfiguring 方法

把你修改后的 OnConfiguring 改回脚手架生成的默认逻辑即可,不需要手动用 ConfigurationManager 读取配置:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        optionsBuilder.UseSqlServer("Data Source=DEX-LEP3LOXH0M5\\SQLEXPRESS;Initial Catalog=LibraryStore;Integrated Security=True");
    }
}

如果不需要本地调试的 fallback 逻辑,也可以直接删除 if 块内的所有代码。

步骤2:修正控制器的 DbContext 调用方式

不要手动 new 上下文实例,改为通过构造函数依赖注入获取已配置好的实例:

[ApiController]
[Route("[controller]")]
public class LibraryController : ControllerBase
{
    private readonly LibraryStoreContext _context;

    // 通过构造函数注入上下文
    public LibraryController(LibraryStoreContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("GetAllDetails")]
    public IEnumerable<LibraryInfo> GetDetails()
    {
        // 直接用注入的实例查询,不需要手动创建释放
        return _context.LibraryDetails.ToList();
    }
}

修改完成后,Startup 中配置的连接串会自动生效,不会再触发 OnConfiguring 里的 fallback 逻辑,报错就会消失。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:18:02