ASP.NET Core系列:读取配置文件

1. 控制台应用

   新建一个控制台应用,添加两个Package:

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

1.1 单个配置文件

  创建配置文件appsettings.json:

{
  "Data": "10000",
  "ConnectionStrings": {
    "DevContext": "开发库",
    "ProdContext": "生产库"
  }
}

  读取配置文件:

using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            var config = builder.Build();

            Console.WriteLine(config["Data"]); // 配置键
            Console.WriteLine(config.GetSection("ConnectionStrings:DevContext").Value); // 分层键
        }
    }
}

  通过ConfigurationBuilder对象来创建ConfigurationRoot对象,进行读取配置文件。

  SetBasePath:设置配置文件基础路径

  AddJsonFile:添加读取的Json文件

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

  配置文件可选及修改自动加载设置:

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");

  配置键约定:

  (1)键不区分大小写。 例如,ConnectionString 和 connectionstring 被视为等效键。

  (2)分层键使用冒号分隔符 (:)

1.2 多个配置文件

  AddJsonFile:添加多个配置文件。

var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);
{
  "Data": "10000",
  "ConnectionStrings": {
    "DefaultContext": "默认库"
  }
}
appsettings.json
{
  "Data": "10000",
  "ConnectionStrings": {
    "DefaultContext": "开发库"
  }
}
appsettings.Development.json
using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile("appsettings.Development.json");
            var config = builder.Build();

            Console.WriteLine(config.GetConnectionString("DefaultContext")); // 输出:开发库
        }
    }
}
using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.Development.json")
                .AddJsonFile("appsettings.json");
            var config = builder.Build();

            Console.WriteLine(config.GetConnectionString("DefaultContext")); // 输出:默认库
        }
    }
}

  配置键相同时,读取选择最后一个添加的文件(AddJsonFile)。

  若要读取所有添加文件的配置信息,可遍历ConfigurationRoot的Providers属性。

using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddJsonFile("appsettings.Development.json");
            var config = builder.Build();

            foreach (var provider in config.Providers)
            {
                provider.TryGet("ConnectionStrings:DefaultContext", out string defaultContext);
                Console.WriteLine(defaultContext);
            }

            // 输出:默认库
            //      开发库
        }
    }
}

1.3 配置读取绑定

  (1)Key读取(键值对)

{
  "AppID": 10000,
  "Node": {
    "ID": "1",
    "Text": "节点"
  }
}
var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");
var config = builder.Build();

var appID = config["AppID"];
var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json");
var config = builder.Build();

var nodeid = config.GetSection("Node").GetSection("ID").Value;

  (2)绑定简单数据类型 GetValue<T>

  添加Package:Microsoft.Extensions.Configuration.Binder

using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            var config = builder.Build();

            var appID = config.GetValue<int>("AppID");
            Console.WriteLine(appID);
        }
    }
}

  (3)绑定到类对象  Get<T>

using System;
using System.Collections.Generic;
using System.Text;

namespace Libing.Core.ConsoleApp
{
    public class Node
    {
        public int ID { get; set; }

        public string Text { get; set; }
    }
}
Node.cs
using System;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            var config = builder.Build();

            var node = config.GetSection("Node").Get<Node>();

            Console.WriteLine("{0}-{1}", node.ID, node.Text);
        }
    }
}

  (4)绑定集合对象

{
  "Node": {
    "ID": 1,
    "Text": "节点",
    "Children": [
      {
        "ID": 11,
        "Text": "子节点1"
      },
      {
        "ID": 12,
        "Text": "子节点2"
      },
      {
        "ID": 13,
        "Text": "子节点3"
      }
    ]
  }
}
appsettings.json
using System;

using System.Collections.Generic;

using System.IO;
using Microsoft.Extensions.Configuration;

namespace Libing.Core.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(cfg =>
                {
                    cfg.Path = "appsettings.json";
                    cfg.Optional = false;
                    cfg.ReloadOnChange = true;
                });
            var config = builder.Build();

            var children = config.GetSection("Node:Children").Get<IEnumerable<Node>>();
            foreach (var child in children)
            {
                Console.WriteLine("{0}-{1}", child.ID, child.Text);
            }
        }
    }
}

2. API应用程序

  新建API应用程序,在根目录下自动创建的Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

其中,CreateDefaultBuilder创建默认配置,包括:

  (1)加载IConfiguration配置,读取文件appsettings.json;

  (2)加载IConfiguration配置,读取文件appsettings.[EnvironmentName].json;

  (3)......

2.1 ConfigureServices中键值读取

  在根目录下文件Startup.cs中ConfigureServices()中采用键值对方式读取:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    int appid = Configuration.GetValue<int>("AppID");
    var nodes = Configuration.GetSection("Node:Children").Get<IEnumerable<Node>>();
}

2.2 ConfigureServices中使用Options

  添加安装包:Microsoft.Extensions.Options.ConfigurationExtensions

{
  "Node": {
    "ID": 1,
    "Text": "NodeText"
  }
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddOptions();
    services.Configure<Node>(Configuration.GetSection("Node"));
}

  在控制器中,通过构造函数注入,读取配置。

public class LogController : ControllerBase
{
    private Node node;
    public LogController(IOptions<Node> option)
    {
        node = option.Value;
    }

    [HttpGet]
    public Node Get()
    {
        int id = node.ID;
        string text = node.Text;

        return node;
    }
}

2.3 读取自定义配置文件

  在项目根目录下,新建配置文件 config.json:

{
  "AppID": "10000"
}

  修改Program.js,增加读取config.json文件。

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("config.json", optional: true, reloadOnChange: true);
        })
        .UseStartup<Startup>();
}

  在Startup.cs中调用:

public void ConfigureServices(IServiceCollection services)
{
    // 省略其它代码...
    string appid = Configuration.GetSection("AppID").Value;
}

2.4 独立类中读取配置

  在.Net Framework中,ConfigurationManager类用于读取配置文件。但在.Net Core中没有该类,新建类ConfigurationManager用于读取配置文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Libing.Portal.Core.Api.Common.Configs
{
    public static class ConfigurationManager
    {
        public readonly static IConfiguration Configuration;

        static ConfigurationManager()
        {
            Configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .Build();
        }

        public static T GetSection<T>(string key) where T : class, new()
        {
            return new ServiceCollection()
                .AddOptions()
                .Configure<T>(Configuration.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
        }

        public static string GetSection(string key)
        {
            return Configuration.GetValue<string>(key);
        }
    }
}
posted @ 2019-08-09 11:54  libingql  阅读(15240)  评论(1编辑  收藏  举报