我有一个带有appsetting.json文件的AspnetCore项目:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConectionStrings": {
"DB": "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=ENIAC"
}
}
现在我得到此设置,并使用以下代码将其注入到控制器中:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<IConfiguration>(Configuration);
}
并且在我的控制器中,我尝试使用以下代码访问连接字符串:
public HomeController(IConfiguration _config) {
config = _config;
var t = config.GetConnectionString("DB");
Debug.WriteLine(t);
}
但是t
现在为空。
我的错误在哪里?我该如何解决这个问题?
答案 0 :(得分:1)
您的appsettings.json文件中有一个错字:ConectionStrings
应该是ConnectionStrings
。