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

时间:2019-12-08 15:56:43

标签: asp.net .net-core .net-core-3.0

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

1 个答案:

答案 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": "............."
  }
}