当我尝试从数据库中检索数据时,出现Object reference not set to an instance of an object
错误。我知道EF可以使用dbcontext,但是我想在我的同事使用这种方法时尝试这种方法。我可以很好地获取ConnectionString,可以在断点处看到它,但是在那一行之后,出现了错误:
System.Configuration.ConnectionStringSettingsCollection.this [string] .get返回null
我的代码如下:
appsettings.json
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-MIHT9TM\\SQLEXPRESS;Database=react_db;User=sa;Password=OtlPHP07"
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services
.AddMvc(options =>
{
options.EnableEndpointRouting = false;
})
.AddNewtonsoftJson()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.WriteIndented = true;
});
services.AddSingleton<IConfiguration>(Configuration);
}
DepartmentController.cs
[Route("api/[controller]")]
[ApiController]
public class DepartmentController : ControllerBase
{
private readonly IConfiguration configuration;
public DepartmentController(IConfiguration configuration)
{
this.configuration = configuration;
}
[HttpGet]
public IActionResult Get()
{
DataTable table = new DataTable();
string query = @"SELECT * FROM dbo.Departments";
var conString = configuration.GetConnectionString("DefaultConnection");
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[conString].ConnectionString))
{
using (var cmd = new SqlCommand(query, con))
{
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.Text;
da.Fill(table);
}
}
}
return Ok(table);
}
}
我在此行遇到错误:using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[conString].ConnectionString))
这是conString的值
我什至尝试了这段代码...
var conString = configuration.GetConnectionString("DefaultConnection");
using (var con = new SqlConnection(ConfigurationManager.AppSettings[conString].ToString()))
答案 0 :(得分:1)
在SqlConnection上,尝试使用在构造函数上传递的配置对象,而不是它的新实例。甚至更好的是您已经拥有的conString变量(它确实使用了在构造函数上传递的配置实例)