我对json配置文件中的连接字符串有疑问, 像往常一样:
我已阅读并尝试插入相关问题中的所有建议: 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_ App设置: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返回空值的问题。 有任何帮助,谢谢
答案 0 :(得分:4)
将此结构用于connectionString
{
"ConnectionStrings": {
"DefaultConnection": "xxx"
}
}
检查您错过s
的json文件,它应该是ConnectionStrings
并以这种简单的方式访问您的连接字符串
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
在您的情况下,DefaultConnection
应该为testConnection
答案 1 :(得分:0)
我尝试将整个connectionString插入到 configuration.GetConnectionString(“ Here”);
但是您是否尝试更改:
options.UseSqlServer(Configuration.GetConnectionString("testConnection"));
到
options.UseSqlServer("your connection string");
另外,您提到您有config.json
和config.development.json
,但是它们应该分别是appsettings.json
和appsettings.development.json