System.Configuration.ConnectionStringSettingsCollection.this [string] .get在ASP.Net Core上返回null

I get an error of Object reference not set to an instance of an object when I try to retrieve my data from a database. I know that EF has a dbcontext that I can use, but I want to try this approach as my colleagues use this kind. I can get the ConnectionString fine, I see it in my breakpoint, but after that line, I get the error System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null. Please see my codes below

appsettings.json

"AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-MIHT9TM\\SQLEXPRESS;Database=react_db;User=sa;Password=OtlPHP07"
  }

启动文件

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);
        }
    }

I encounter the error on this line: using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings[conString].ConnectionString))

你能帮我吗?谢谢。

编辑

这是conString的值

enter image description here

我事件尝试了此代码...

var conString = configuration.GetConnectionString("DefaultConnection");
            using (var con = new SqlConnection(ConfigurationManager.AppSettings[conString].ToString()))
评论
女人!依旧
女人!依旧

在SqlConnection上,尝试使用在构造函数上传递的配置对象,而不是它的新实例。甚至更好的是您已经拥有的conString变量(它确实使用了在构造函数上传递的配置实例)

点赞
评论