.net core实现读取appsettings.json配置文件(

转自:https://www.cnblogs.com/jiyuwu/p/11776044.html

第一种直接放到通用类库,那里想调往那调。

1.编辑我们的appsettings.json文件

.net core实现读取appsettings.json配置文件(
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "ConnectionStrings": {
    "TestConnection": "server=123;User ID=jiyuwu;Password=123456;database=jiyuwu;",
    "Redis": "127.0.0.1:6379"
  },
  "AllowedHosts": "*"
}
.net core实现读取appsettings.json配置文件(

.net core实现读取appsettings.json配置文件(

 

 

 2.通用类库Common添加引用类库Microsoft.Extensions.Configuration.Json并添加AppSettingsHelper.cs

Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0

.net core实现读取appsettings.json配置文件(

.net core实现读取appsettings.json配置文件(
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
        public class AppSettingsHelper
        {
            public static IConfiguration Configuration { get; set; }
            static AppSettingsHelper()
            {
                //ReloadOnChange = true 当appsettings.json被修改时重新加载            
                Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                .Build();
            }

        }
    }
.net core实现读取appsettings.json配置文件(

3.调用

string sqlString= AppSettingsHelper.Configuration.GetConnectionString("TestConnection");
string sqlString1 = AppSettingsHelper.Configuration["Logging:LogLevel:Default"];

.net core实现读取appsettings.json配置文件(

 

 

第二种直接读文件调用。

1.引用类库并读取文件获取配置

Install-Package Microsoft.Extensions.Configuration.Json -Version 3.0.0
.net core实现读取appsettings.json配置文件(
public IConfiguration Configuration;
public void TestAppSettings()
        {
            var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Configuration = builder.Build();
            string sqlString2 = Configuration["Logging:LogLevel:Default"];
        }
.net core实现读取appsettings.json配置文件(

.net core实现读取appsettings.json配置文件(

 

 

简单介绍下原理:

我们通过ConfigurationBuilder对象来创建ConfigurationRoot对象,并用其来读取配置。SetBasePath()方法是用来设置我们配置对象需要的配置文件的基础路径,比如我们将基础路径设置为C:\TemplateCore\TemplateCore,那么他读取我们的配置文件appsettings.json的路径将是C:\TemplateCore\TemplateCore\appsettings.json

 

 

开源地址:https://github.com/jiyuwu/TemplateCore

测试浏览效果:http://127.0.0.1:1994/home/TestAppSettings

.net core实现读取appsettings.json配置文件(

.net core实现读取appsettings.json配置文件(

上一篇:阿里毕玄:程序员应如何选择职业成长路线?


下一篇:php5.6版本安装出错 make: *** [ext/fileinfo/libmagic/apprentice.lo] Error 1