1.appsettings.json文件添加完整的链接字符串SqlServerConnection

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "SqlServerConnection": "Data Source=.;Initial Catalog=STUDENT;User ID=sa;Password=123456"
  }
}

2.创建ConfigurationHelper类

 public static class ConfigurationHelper
    {
        /// <summary>
        ///  读取json文件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="ParentKey">父级json节点</param>
        /// <param name="childrenKey">子级节点</param>
        /// <param name="path">appsettings.json</param>
        /// <returns></returns>
        public static object GetAppSettings<T>(string parentKey, string childrenKey = null, string path = "appsettings.json")
        {
            object strInfo = string.Empty;
            var builder = new ConfigurationBuilder().AddJsonFile(path);
            var configuration = builder.Build();
            try
            {
                if (!string.IsNullOrWhiteSpace(childrenKey))
                {
                    strInfo = configuration.GetSection(parentKey).GetValue<T>(childrenKey);
                }
                else
                {
                    strInfo = configuration[parentKey].ToString();
                }
                return strInfo;
            }
            catch (Exception ex)
            {
                //LogHelper.Error(ex.Message.ToString());
                return null;
            }
        }
    }

3.提示出现问题引用

Microsoft.Extensions.Options.ConfigurationExtensions
Microsoft.Extensions.Configuration

Microsoft.Extensions.Configuration.FileExtensions

Microsoft.Extensions.Configuration.Json

4.调用读取节点
(1):单独读取 AllowedHosts 节点

var str = ConfigurationHelper.GetAppSettings<object>("AllowedHosts");

(2):读取ConnectionString下面的SqlServerConnection的节点

 var str = ConfigurationHelper.GetAppSettings<object>("ConnectionStrings", "SqlServerConnection");

或者

 var str = ConfigurationHelper.GetAppSettings<object>("ConnectionStrings:SqlServerConnection");
Last modification:December 20th, 2019 at 04:02 pm
如果觉得我的文章对你有用,请随意赞赏