在 web.config 文件中,我有:
<connectionStrings>
<add name="connectionString" connectionString="Data Source=Server; Initial Catalog=DB; Persist Security Info=true; User ID=****; Password=****" />
</connectionStrings>
我尝试在类中使用此连接字符串:
var connString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
但是我得到这个错误:
System.Configuration.ConnectionStringSettingsCollection.this [string] .get 返回null
答案 0 :(得分:0)
我建议在.net核心应用程序中使用 appsettings.json 并从中读取connectionString:
static class class
{
public static IConfigurationRoot Configuration;
public static string GetConnectionString()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
var connectionString = Configuration["ConnectionStrings:connectionString"];
}
}
appsettings.json :
{
"ConnectionStrings": {
"connectionString": "............."
}
}