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

ASP.NET Core MVC & EF Core:更新/删除数据库时连接字符串格式错误求助

解决“Failed creating connection: Format of the initialization string does not conform to specification starting at index 0”错误

在执行数据库更新或删除操作时,抛出以下错误:

Failed creating connection: Format of the initialization string does not conform to specification starting at index 0.

结合你提供的appsettings.json和Startup.cs配置,常规写法没问题,可从以下几个方向排查:

  • 确认配置文件是否被正确加载
    取消注释Startup.cs里的throw new Exception(Configuration.GetConnectionString("DefaultConnection")),运行项目查看异常信息里的连接字符串内容:

    • 如果是空值或乱码,说明配置文件未被正确读取。检查appsettings.json的复制到输出目录属性,设置为「如果较新则复制」或「始终复制」,确保运行时能读取到配置文件。
  • 排查连接字符串的特殊字符
    手动重新输入连接字符串,避免复制粘贴带来的不可见特殊字符(如全角符号、隐藏空格):

    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=AvcolMusic;Trusted_Connection=True;"
    

    也可尝试替换等效参数测试:将Trusted_Connection=True换成Integrated Security=True,部分驱动对参数解析优先级有差异。

  • 验证EF Core包与.NET版本兼容性
    检查Microsoft.EntityFrameworkCore.SqlServer包版本是否和项目.NET版本匹配(如.NET 6对应EF Core 6),版本不兼容可能导致连接字符串解析失败。

  • 排查配置源覆盖问题
    项目若使用环境变量、用户机密等其他配置源,可能会覆盖appsettings.json的连接字符串。可在Startup.cs中添加代码打印所有配置源的连接字符串:

    var allConnectionStrings = Configuration.GetSection("ConnectionStrings").GetChildren();
    foreach (var cs in allConnectionStrings)
    {
        Console.WriteLine($"{cs.Key}: {cs.Value}");
    }
    

    查看是否存在其他配置源的DefaultConnection值为空或格式错误。

  • 硬编码连接字符串测试
    暂时将连接字符串硬编码到UseSqlServer中,验证是否能正常连接:

    options.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=AvcolMusic;Trusted_Connection=True;");
    

    如果硬编码能成功,说明问题出在配置读取环节,而非连接字符串本身。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:00:59