VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > .net教程 >
  • ASP.net教程之Asp .Net Core 读取appsettings.json配置文件

 
    Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的。那么今天给大家介绍下具体如何读取配置文件的。
 
首先创建一个读取配置文件的公共类GetAppsetting,我们可以看下此时配置文件中的内容
复制代码
{
  "GetSetting": {
    "option1": "value1_from_json",
    "option2": -1,
    "subsection": {
      "suboption1": "subvalue1_from_json",
      "suboption2": 200
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}
复制代码
 
 
在创建的GetAppsetting公共类中写如下代码
     
复制代码
   /// <summary>
        /// 实例化、调用GetAppsetting()
        /// </summary>
        /// <param name="builder"></param>
        public static void connection(IConfiguration build)
        {
            getvalue = new GetAppsetting(build);
        }
 
        /// <summary>
        /// 在类中进行连接

        /// </summary>
        public static GetAppsetting getvalue { get; private set; }
 
        /// <summary>
        /// 最终实例化GetAppsetting(配置文件),读取到GetSetting下面的配置

        /// </summary>
        /// <param name="builder"></param>
        public GetAppsetting(IConfigurationbuild)
        {
            this.GetSettings = new GetSetting(build.GetSection("GetSetting"));
        }  
 
        public  GetSetting GetSettings { get; }
        /// <summary>
        /// 获取配置下面的具体属性的值

        /// </summary>
        public class GetSetting
        {
            public string option1 { get; }
            public GetSetting(IConfiguration Configuration)
            {
                this.option1 = Configuration.GetSection("option1").Value;
            }
        }
复制代码
 
最后需要在Program中的Main函数中初始化
复制代码
var Configuration = new ConfigurationBuilder()
             .Add(new JsonConfigurationSource { Path = "appsettings.json",  ReloadOnChange = true })
             .Build();
            GetAppsetting.connection(Configuration);


var a = GetAppsetting.getvalue.GetSettings.option1;//这样我们就可以拿到配置文件中GetSetting下面的option1的属性值了
复制代码
 
 
参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2
           https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2
相关教程