zoukankan      html  css  js  c++  java
  • .net core json配置文件小结

    .net core 中自带的appsettings.json是自动注入了的,这个文件不用说了

    1、appsettings.json下面的appsettings.Development.json和appsettings.Production.json,可以根据不同的环境读取不同的配置文件

    /// <summary>
            /// 获取配置
            /// </summary>
            /// <param name="JsonFileName">json文件路径</param>
            /// <returns></returns>
            public static IConfiguration GetConfiguration(string JsonFilePath)
            {
                IConfiguration Configuration = new ConfigurationBuilder()
                .AddJsonFile(JsonFilePath)
                .Build();
                return Configuration;
            }
    public static IConfiguration getConfiguration()
            {
                var environment = getEnvironment("ASPNETCORE_ENVIRONMENT");
                if (Singleton<IConfiguration>.Instance == null)
                {
                    IConfiguration configuration = null;
                    if (environment == "Development")
                    {
                        configuration = ConfigService.GetConfiguration("appsettings.Development.json");
                    }
                    else if (environment == "Production")
                    {
                        configuration = ConfigService.GetConfiguration("appsettings.Production.json");
                    }
                    Singleton<IConfiguration>.Instance = configuration;
                }
                return Singleton<IConfiguration>.Instance;
            }

    这种配置方式,所有的配置信息都放在一起,看起来可能比较臃肿,但是更适应持续部署,直接通过环境变量来判断测试环境还是生产环境,测试和生产都是一套代码适用于k8s

    2、其他json配置文件

    public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureAppConfiguration((hostingContext, configBuilder) =>
                    {
                        configBuilder
                            .AddJsonFile("Config/Common.json")
                            .AddJsonFile("Config/Ftp.json")
                            .AddJsonFile("Config/Mongo.json")
                            .AddJsonFile("Config/SqlConn.json")
                            .AddJsonFile("Config/Redis.json");
                    })
                    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>().UseUrls("http://*:8080");
                    });

    这里是将配置文件中的配置信息注入到Configuration中,后面可以直接用,注意下各个文件中的key不要相同就行

    每个配置文件都是单一配置,配置结构更清晰,这种方式适合手动发布,测试和生产是两套代码

  • 相关阅读:
    接口测试基础知识
    WebSocket接口怎么做测试
    python的数据类型特点和常用方法
    python封装一个工具类 ,对MySQL数据库增删改查
    python 往MySQL批量插入数据
    python对MySQL进行曾删改查
    Rest Assured从入门到遇到各种问题(汇总、更新)
    jmeter参数化之动态读取csv文件
    Charles 浏览器(火狐)抓包设置
    导入git项目报错"no projects are found to import" 找不到项目
  • 原文地址:https://www.cnblogs.com/jianghaidong/p/14777753.html
Copyright © 2011-2022 走看看