当我在发布配置文件时遇到问题时,我决定使用.net core 3创建一个小型的测试控制台应用程序,并查看是否设置了我的环境变量以及是否正在读取相应的appsettings.json文件。
>所以,开始吧。
Program.json
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Cmd1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var environmentName =
Environment.GetEnvironmentVariable("ENVIRONMENT");
// create service collection
var services = new ServiceCollection();
// build config
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables()
.Build();
// setup config
services.AddOptions();
services.Configure<AppSettings>(configuration.GetSection("App"));
// create service provider
var serviceProvider = services.BuildServiceProvider();
var appSettings = serviceProvider.GetService<IOptions<AppSettings>>();
string env = Environment.GetEnvironmentVariable("Environment");
Console.WriteLine($" We are looking at {appSettings.Value.TempDirectory} from environment: {env}");
}
}
}
appsettings.json
{
"App": {
"TempDirectory": "d:\temp"
}
}
appsettings.Local.json
{
"App": {
"TempDirectory": "c:\\temp\\rss-hero\\tmp\\"
}
}
appsettings.Test.json
{
"App": {
"TempDirectory": "d:\test"
}
}
如果我尝试在命令行上设置环境,它似乎并没有接受。我想念什么? 如果我为此控制台应用程序使用发布配置文件,则会发生类似的问题。
[编辑2] 添加了使用命令行参数的功能后,
if (args != null)
{
if (args.Length > 0)
{
Environment.SetEnvironmentVariable("Environment", args[1]);
}
}