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
相关产品推荐
相关产品推荐

