熟悉ASP.NET的开发者一定对web.config文件不陌生。在ASP.NET环境中,要想添加配置参数,一般也都会在此文件中操作。其中最常用的莫过于AppSettings与ConnectionStrings两项。而要在代码中获得文件中的配置信息,ConfigurationManager则是必不可少需要引入的程序集。
然而到了ASP.NET Core时代,存储与读取配置的方式都发生了改变。
如果对ASP.NET Core项目有所了解的话,应该会看到过appsettings.json这个文件。这里就从JSON文件配置方式开始解释ASP.NET Core中是如何读取配置信息的。
假设有预先设置的appsettings.json文件:
{ "option1": "value1_from_json", "option2": 2, "subsection": { "suboption1": "subvalue1_from_json" }, "wizards": [ { "Name": "Gandalf", "Age": "1000" }, { "Name": "Harry", "Age": "17" } ]}
在代码中读取可以按下面的方式操作:
public class Program{ public static IConfiguration Configuration { get; set; } public static void Main(string[] args = null) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); Console.WriteLine($"option1 = {Configuration["Option1"]}"); Console.WriteLine($"option2 = {Configuration["option2"]}"); Console.WriteLine( $"suboption1 = {Configuration["subsection:suboption1"]}"); Console.WriteLine(); Console.WriteLine("Wizards:"); Console.Write($"{Configuration["wizards:0:Name"]}, "); Console.WriteLine($"age {Configuration["wizards:0:Age"]}"); Console.Write($"{Configuration["wizards:1:Name"]}, "); Console.WriteLine($"age {Configuration["wizards:1:Age"]}"); Console.WriteLine(); Console.WriteLine("Press a key..."); Console.ReadKey(); }}
首先,实例化一个ConfigurationBuilder对象,接着设置基础路径。
SetBasePath的操作其实是在ConfigurationBuilder的属性字典里设置FileProvider的值。public static IConfigurationBuilder SetBasePath(this IConfigurationBuilder builder, string basePath){ ... return builder.SetFileProvider(new PhysicalFileProvider(basePath));}public static IConfigurationBuilder SetFileProvider(this IConfigurationBuilder builder, IFileProvider fileProvider){ ... builder.Properties[FileProviderKey] = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider)); return builder;}
然后是添加JSON文件。
public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange){ ... return builder.AddJsonFile(s => { s.FileProvider = provider; s.Path = path; s.Optional = optional; s.ReloadOnChange = reloadOnChange; s.ResolveFileProvider(); });}public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action<JsonConfigurationSource> configureSource) => builder.Add(configureSource);
新闻热点
疑难解答
图片精选