.NetCore3.0配置Configuration的方法-创新互联-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
.NetCore3.0配置Configuration的方法-创新互联

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

成都做网站、网站设计介绍好的网站是理念、设计和技术的结合。成都创新互联拥有的网站设计理念、多方位的设计风格、经验丰富的设计团队。提供PC端+手机端网站建设,用营销思维进行网站设计、采用先进技术开源代码、注重用户体验与SEO基础,将技术与创意整合到网站之中,以契合客户的方式做到创意性的视觉化效果。

准备

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

.Net Core3.0 配置Configuration的方法

错误提示:error : The project file cannot be opened by the project system, because it is missing some critical imports or the referenced SDK cannot be found. Detailed Information:

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

.Net Core3.0 配置Configuration的方法

开始

新建个Asp.net Core 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(prefix: "DOTNET_");
        if (args != null)
        {
          config.AddCommandLine(args);
        }
      });

      builder.ConfigureAppConfiguration((hostingContext, config) =>
      {
        var env = hostingContext.HostingEnvironment;

        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
           .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

        if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
        {
          var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
          if (appAssembly != null)
          {
            config.AddUserSecrets(appAssembly, optional: true);
          }
        }

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

.Net Core3.0 配置Configuration的方法

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

  • Logging:LogLevel:Default

  • Logging:LogLevel:System

  • Logging:LogLevel:Microsoft

  • Logging:LogLevel:Microsoft.Hosting.Lifetime

  • AllowedHosts

var jsonValue = $"AllowedHosts:{_config["AllowedHosts"]}"+ "\r\n";
      jsonValue += "Logging:LogLevel:Default:" + _config.GetValue("Logging:LogLevel:Default")+ "\r\n";

      //GetSection 返回IConfigurationSection;如果未匹配到 返回null
      //jsonValue += "---" + _config.GetSection("Logging:LogLevel:System");
      jsonValue += "Logging:LogLevel:System:" + _config.GetSection("Logging:LogLevel:System").Value+ "\r\n\n";
     
      var logSection = _config.GetSection("Logging:LogLevel");
      var configurationSections = logSection.GetChildren();
      foreach (var sections in configurationSections) 
      {
        jsonValue += $"{sections.Path}:{sections.Value}";
        jsonValue += "\r\n";
      }
      jsonValue += "\r\n";

.Net Core3.0 配置Configuration的方法

配置指定json文件绑定至类

新建一个json文件-AAAppSettings.json

{
 "AA": {
  "RabbitMqHostUrl": "rabbitmq://localhost:5672",
  "RabbitMqHostName": "localhost",
  "RabbitMqUserName": "admin",
  "RabbitMqPassword": "123"
 }
}

使用ConfigureAppConfiguration方法配置指定的json文件

public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
      .ConfigureAppConfiguration((hostingContext, config) =>
      {
        config.SetBasePath(Directory.GetCurrentDirectory());
        config.AddJsonFile("AAAppSettings.json", optional: true, reloadOnChange: true);
      })

使用bind方法绑定到新建的类上如:

public partial class AAConfig
  {
    public string RabbitMqHostUrl { get; set; }
    public string RabbitMqHostName { get; set; }
    public string RabbitMqUserName { get; set; }
    public string RabbitMqPassword { get; set; }
  }
var aaConfig = new AAConfig();
_config.GetSection("AA").Bind(aaConfig);
jsonValue += aaConfig.RabbitMqHostUrl + "\r\n";
jsonValue += aaConfig.RabbitMqHostName + "\r\n";
jsonValue += aaConfig.RabbitMqUserName + "\r\n";
jsonValue += aaConfig.RabbitMqPassword + "\r\n";
return jsonValue;

运行输出:

.Net Core3.0 配置Configuration的方法

感谢各位的阅读,以上就是“.Net Core3.0 配置Configuration的方法”的内容了,经过本文的学习后,相信大家对.Net Core3.0 配置Configuration的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联网站建设公司,,小编将为大家推送更多相关知识点的文章,欢迎关注!


新闻标题:.NetCore3.0配置Configuration的方法-创新互联
文章网址:http://scgulin.cn/article/gcdjh.html