当前位置:网站首页>ASP. Net core reads the configuration file in the class library project

ASP. Net core reads the configuration file in the class library project

2022-04-23 17:04:00 begeneral

Go straight to the code :

public static string ReadConnectString(string connectName)
        {
            var config = new ConfigurationBuilder().Add(new JsonConfigurationSource()
            {
                Path = "appsettings.json",
                Optional = true
            }).Build();
            var connectionString = config.GetConnectionString(connectName);
            if(string.IsNullOrEmpty(connectionString))
            {
                LogHelper.WriteErrorLog($" stay appsettings.json in , Could not find name {connectName} Connection string of ");
                return null;
            }
            return connectionString;
        }

The configuration file is as follows :

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database= Database name ;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Follow this configuration file , The parameter passed in by the above function should be :DefaultConnection.

I want to introduce 2 An assembly :

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

What I write here is read only appsettings.json The connection string inside , If you want to read the custom configuration , Call GetSection.

版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554082264.html