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

ASP.NET Core 5搭配EF Core脚手架生成API控制器报连接字符串为空错误

问题解决方案

该报错由两处拼写错误导致连接字符串读取为空:

  • Startup.cs中读取连接字符串的键名拼写错误:代码中填写的键名为DefaultConection,比appsettings.json中定义的DefaultConnection少了字母n,导致读取配置返回null
  • appsettings.json中的连接字符串存在语法错误:Initial,Catalog中间多写了逗号,正确格式为Initial Catalog

修正后的配置代码

1. appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection":"Data Source=DESKTOP-THJSEM4;Initial Catalog=M_VPSA_V3;Integrated Security=True"
  }
}

2. Startup.cs ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddDbContext<M_VPSA_V3Context>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API_MOBEXX", Version = "v1" });
            });
}

修正后重新编译项目,再执行脚手架生成API控制器操作即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:45:03