.net core 根据环境变量区分正式、测试 配置文件

mac2022-06-30  10

新建测试、正式环境下所用的 配置信息文件

 

appsettings.Development.json 文件信息:

{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "db": { "mysql": { "conStr": "xxxxxxxxxxxxxxxxx", //测试 "providerName": "MySql.Data.MySqlClient" }, "redis": { "conStr": "xxxxxxxxxxxxxxxxx", //测试 "dbId": "3" } }, "ThOcUrl": "xxxxxxxxxxxxxxxxx", //测试 "ThSftpInfo": "xxxxxxxxxxxxxxxxx", //测试 "ThFileUrl": "xxxxxxxxxxxxxxxxx" //测试 }

加入相关nuget引用

添加获取配置信息帮助类

using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using System; using System.IO; using Microsoft.Extensions.DependencyInjection; namespace YanWenCore.ThregGoods.Common { public static class MyServiceProvider { public static IServiceProvider ServiceProvider { get; set; } } public class AppSettingHelper { //根据环境变量配置获取json文件的名称 private static readonly string AppSettingName = String.Format("appsettings.{0}.json", MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>().EnvironmentName); private static IConfigurationRoot configR; static AppSettingHelper() { var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(AppSettingName); configR = builder.Build(); } public static IConfigurationRoot GetRotConfig() { if (configR == null) { configR = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile(AppSettingName).Build(); } return configR; } //Mysql连接 public static string MysqlConnectionStringSettings { get { return GetRotConfig().GetSection("db").GetSection("mysql").GetSection("conStr").Value; } } //Redis连接信息 public static string RedisConnectionStringSettings { get { return GetRotConfig().GetSection("db").GetSection("redis").GetSection("conStr").Value; } } //OC平台接口地址 public static string GetbatteryCertUrl { get { return GetRotConfig().GetSection("ThOcUrl").Value; } } //sftp服务器信息 public static string ThSftpInfo { get { return GetRotConfig().GetSection("ThSftpInfo").Value; } } //文件服务器地址 public static string ThFileUrl { get { return GetRotConfig().GetSection("ThFileUrl").Value; } } } }  

应用程序期间提供初始化提供服务容器的对象

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } MyServiceProvider.ServiceProvider = app.ApplicationServices; }

 

执行docker run 之前,设置环境变量

set ASPNETCORE_ENVIRONMENT= Development

 

转载于:https://www.cnblogs.com/-xyl/p/11435445.html

最新回复(0)