当我在本地使用 VS Code 进行开发时,我将使用端口 3000,因为我是一个时髦人士。非时髦人士希望它位于服务器上的端口 8080 上。太好了,我们明白了。 Microsoft 文档给我以下示例:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile("hosting.json", optional: true)
.AddCommandLine(args)
.Build();
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.Configure(app =>
{
app.Run(async (context) => await context.Response.WriteAsync("Hi!"));
})
.Build();
host.Run();
}
我不想使用 hosting.json
。我为什么要那个?对于这种情况,我有这个 appsettings.{environment}.json
文件。亲爱的,我会把那个坏男孩粘贴进去
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddCommandLine(args)
.Build();
什么是编译错误? env
在当前上下文中不存在。它只存在于 Startup.cs
文件中 -- 启动时不调用它,而是从启动文件 Program.cs
中调用,用魔法。
那么,我该如何解决这个问题呢?如何将特定于环境的托管设置存储在特定于环境的 appsettings.json
中,然后在通过 WebHostBuilder
构建特定于环境的 Web 主机时使用它Program.cs
?
最佳答案
这是可能的。扩展给出的答案 here ,通过在 Program.cs 中创建 WebHostBuilder 和 ConfigurationBuilder,可以访问主机环境,然后在环境特定的应用程序设置文件中配置主机 URL 和端口。
假设一个 appsettings.json 和一个 apppsettings.Development.json 文件分别包含以下内容:
"hostUrl": "http://*:<port number here>"
使用以下内容修改 Main:
public static void Main(string[] args)
{
var host = new WebHostBuilder();
var env = host.GetSetting("environment");
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true)
.AddEnvironmentVariables();
var configuration = builder.Build();
host.UseKestrel()
.UseUrls(configuration["hostUrl"])
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build()
.Run();
}
使用此代码,Startup.cs 仍需要声明其自己的 ConfigurationBuilder 以便公开其 Configuration 属性。
关于c# - 使用 appsettings 驱动特定于环境的设置,例如 UseUrls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254585/