net Core3.0配置配置的方法

  介绍

这篇文章主要讲解了。”净Core3.0配置配置的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习”。净Core3.0配置配置的方法”吧!

<强>准备

。网络核心和。NET项目配置上有了很大的改变,支持的也更加丰富了比如命令行,环境变量、内存中。NET对象,设置文件等等。净项目我们常常把配置信息放到webConfig或者appConfig中。配置相关的源码https://github.com/aspnet/Extensions;如果打开源码项目如果遇到以下错误,未遇到直接跳过。

。净Core3.0配置配置的方法

错误提示:错误:项目的项目文件不能打开系统,因为它缺少一些关键进口或无法找到引用的SDK。详细信息:

解决办法:查看本地安装的sdk与全球。json中制定的版本是否一致,然后修改即可

。净Core3.0配置配置的方法

<强>开始

新建个Asp.net核心web应用程序系统默认创建了appsettings。json;在应用启动生成主机时调用CreateDefaultBuilder方法,默认会加载appsettings。json。代码如下:

public  static  IHostBuilder  CreateDefaultBuilder (string [], args)   ,,,{   ,,,,,var  builder =, new  HostBuilder ();      ,,,,,builder.UseContentRoot (Directory.GetCurrentDirectory ());   ,,,,,builder.ConfigureHostConfiguration (config =比;   ,,,,,{   ,,,,,,,config.AddEnvironmentVariables(前缀:“DOTNET_");   ,,,,,,,if  (args  !=, null)   ,,,,,,,{   ,,,,,,,,,config.AddCommandLine (args);   ,,,,,,,}   ,,,,,});      ,,,,,builder.ConfigureAppConfiguration ((hostingContext,配置),=比;   ,,,,,{   ,,,,,,,var  env =, hostingContext.HostingEnvironment;      ,,,,,,,config.AddJsonFile (“appsettings.json",,可选:,真的,,reloadOnChange:,真的)   ,,,,,,,,,,.AddJsonFile(美元“appsettings。{env.EnvironmentName} .json",,可选,,真的,,reloadOnChange:, true);      ,,,,,,,if  (env.IsDevelopment (),,,, ! string.IsNullOrEmpty (env.ApplicationName))   ,,,,,,,{   ,,,,,,,,,var  appAssembly =, Assembly.Load (new  AssemblyName (env.ApplicationName));   ,,,,,,,,,if  (appAssembly  !=, null)   ,,,,,,,,,{   ,,,,,,,,,,,config.AddUserSecrets (appAssembly,可选:真正的);   ,,,,,,,,,}   ,,,,,,,}

利用GetValue, GetSection, GetChildren读取appsettings。json键值对。我们打开appsettings。json文件:

。净Core3.0配置配置的方法

将文件读入配置时,会创建一下唯一的分层健来保存配置值:

<李>

日志:LogLevel:默认

<李>

日志:LogLevel:系统

<李>

日志:LogLevel:微软

<李>

日志:LogLevel: Microsoft.Hosting。李一生

<李>

AllowedHosts

var  jsonValue =,美元“AllowedHosts: {_config [“AllowedHosts"]}“+,“\ r \ n";   ,,,,,jsonValue  +=,“日志:LogLevel:默认值:“,+,_config.GetValue(“日志:LogLevel: Default") +,“\ r \ n";      ,,,,,//GetSection 返回IConfigurationSection;如果未匹配到,返回零   ,,,,,//jsonValue  +=,“——产生绯闻;,+,_config.GetSection(“日志:LogLevel:煤气报修);   ,,,,,jsonValue  +=,“日志:LogLevel:系统:“,+,_config.GetSection(“日志:LogLevel:煤气报修)value +,“\ r \ n \ n";   ,,,,   ,,,,,var  logSection =, _config.GetSection(“日志:LogLevel");   ,,,,,var  configurationSections =, logSection.GetChildren ();   ,,,,,foreach  (var  sections  configurationSections拷贝),   ,,,,,{   ,,,,,,,jsonValue  +=,美元“{sections.Path}: {sections.Value}“;   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

net Core3.0配置配置的方法