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

.NET ASP Core添加健康检查后DbContext连接字符串空引用问题求助

.NET ASP Core 添加DbContext时的空引用错误解决方法

问题场景

我正在开发一个使用SSMS(SQL Server Management Studio)数据库的.NET ASP Core应用程序,原本在Startup.cs文件中通过以下代码向IServiceCollection添加DatabaseContext运行正常:

services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(_config.GetConnectionString("MvcMovieContext")));

但在引入Microsoft.Extensions.Diagnostics.HealthChecks实现健康检查后,上述代码突然出现错误提示:

Possible null reference argument for parameter 'connectionString' in 'DbContextOptionsBuilder SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, string connectionString, Action<SqlServerDbContextOptionsBuilder>? sqlServerOptionsAction = null)

同时,若尝试将连接字符串存入变量(如string conn = _config.GetConnectionString("MvcMovieContext");),还会触发“converting null literal or possible null value to non-nullable types”错误。

解决方案

感谢@MindSwipe的建议,通过对连接字符串进行非空校验即可修复问题,代码示例如下:

var connectionString = _config.GetConnectionString("MvcMovieContext");
if (connectionString is not null) 
{
    services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:22:05