.NET|.NET Core自定义配置文件

前文讲获取配置文件内容的时候,是获取默认的appsettings.json配置文件的配置,下面说明下如何进行自定义配置文件获取
1. Json Provider 1.1 构建独立的IConfiguration
编写方法

public static IConfigurationRoot LoadSettings(this IHostEnvironment env){return new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("common.json", optional: true, reloadOnChange: false).AddJsonFile("appsettings.json", optional: true, reloadOnChange: false).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false).AddEnvironmentVariables().Build(); }

在Startup构造函数的时候进行赋值替换IConfiguration
private readonly IConfiguration _configuration; public Startup(IWebHostEnvironment env){_configuration = env.LoadSettings(); }

该操作添加的配置项,只在startup范围生效。
1.2 在Progrom全局自定义配置
public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{var env = hostingContext.HostingEnvironment; config.SetBasePath(env.ContentRootPath); config.AddJsonFile("devappsettings.json", optional: false, reloadOnChange: true); }).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup(); });

注意:添加自定义文件的目录要注意,可能会存在因为目录问题所以找不到配置文件的情况。
2. Memory Provider 允许我们将一个应用程序配置直接配置到内存中,而不是像传统方式那样子必须制定一个物理文件。
var builder = new ConfigurationBuilder(); var profileCollection = new Dictionary{{"AuthorProfile:FirstName", "Joydip"},{"AuthorProfile:LastName", "Kanjilal"},{"AuthorProfile:Address", "Hyderabad, India"}}; builder.AddInMemoryCollection(profileCollection); Configuration = builder.Build();

使用
public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{var builder = new ConfigurationBuilder(); var profileCollection = new Dictionary{{"AuthorProfile:FirstName", "Joydip"},{"AuthorProfile:LastName", "Kanjilal"},{"AuthorProfile:Address", "Hyderabad, India"}}; builder.AddInMemoryCollection(profileCollection); config.AddConfiguration(builder.Build()); }).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup(); });

然后就可以通过IConfiguration实例去获取了。
3. 公共类获取配置文件 引用组件
Microsoft.Extensions.Configuration.Json
public class AppSettings{private static IConfiguration Configuration { get; set; }public AppSettings(IConfiguration configuration){Configuration = configuration; }/// /// 封装要操作的字符/// /// /// public static string GetValue(params string[] sections){try{if (sections.Any())return Configuration[string.Join(":", sections)]; }catch (Exception){ }return ""; }/// /// 递归获取配置信息数组///引用 Microsoft.Extensions.Configuration.Binder 包/// /// /// 【.NET|.NET Core自定义配置文件】/// public static List App(params string[] sections){List list = new List(); Configuration.Bind(string.Join(":", sections), list); return list; }}

ConfigureServices中配置
services.AddSingleton(new AppSettings(Configuration));

获取指定配置
var info = AppSettings.GetValue("Logging", "LogLevel");

到此这篇关于.NET Core自定义配置文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读