connectionString不能为空值 - c#

我对json配置文件中的连接字符串有疑问,
照常 :

我创建了一个类:applicationDbcontext
我做了一个DbSet {get; set;}
将其集成到控制器中
将其添加到服务

我已阅读并尝试插入相关问题中的所有建议:
asp.net core 2.0 - Value cannot be null. Parameter name: connectionString
但是他们都不跟我一起工作
这是我的实现,
希望有人能帮助我,谢谢

A_ DB上下文:

   public class ApplicationDbContext:DbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
            Database.EnsureCreated();
        }
        public DbSet<Person> Persons { get; set; }
    }
}

B_应用程序设置:config.json和config.development.json

{
    "ConnectionString": {
        "testConnection": "Server=(localdb)\\mssqllocaldb;Database=mvc_db;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
        "LogLevel": {
            "Default": "Warning"
        }
    },
    "AllowedHosts": "*"

}

C_服务注入

启动 :

  public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.Json")
                .AddJsonFile("appsettings.Development.Json", true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

配置服务:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<ApplicationDbContext>(options => {
                options.UseSqlServer(Configuration.GetConnectionString("testConnection"));
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

D_注入控制器:

 private readonly ApplicationDbContext _db;
        public PersonController(ApplicationDbContext db)
        {
            _db = db;
        }

        IEnumerable<Person> People { get; set; }
        public IActionResult Index()
        {
            People = _db.Persons.ToList();
            return View(People);
        }

我试图将整个connectionString插入configuration.GetConnectionString(“ Here”);中;
并将连接字符串的位置从上向下更改,反之亦然。
但是没有任何方法可以解决connectionString返回空值的问题。
任何帮助,请感谢connectionString不能为空值 - c#

参考方案

对connectionString使用此结构

 {

 "ConnectionStrings": {
  "DefaultConnection": "xxx"
   }
}

检查您错过了s的json文件,它应该是ConnectionStrings

并以这种简单的方式访问您的连接字符串

   services.AddDbContext<ApplicationDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

您的情况DefaultConnection应该是testConnection

45码