System.Configuration.ConnectionStringSettingsCollection.this[string].get 在 class 中返回 null

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null in class

web.config 文件中我有:

  <connectionStrings> 
    <add name="connectionString" connectionString="Data Source=Server; Initial Catalog=DB; Persist Security Info=true; User ID=****; Password=****" />
  </connectionStrings>

我尝试在 class 中读取此连接字符串:

var connString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

但是我得到这个错误:

System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null

我建议在 .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": "............."
  }
}