c# - 使用 appsettings 驱动特定于环境的设置,例如 UseUrls

标签 c# asp.net-core asp.net-core-mvc visual-studio-code asp.net-core-webapi

当我在本地使用 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/

相关文章:

razor - 为什么我需要启用 Razor 运行时编译?我在吃疯狂的药吗?

c# - Windows Phone 7 - App.ViewModel 重复项

c# - 在 WebClient (C#/.net) 中发布数组

asp.net-core - 是否可以/应该使用 IdentityServer4 创建用于用户电子邮件验证的 token

json - 您可以预览 ASP.NET Core 的 appsettings.json 环境覆盖吗?

c# - 带有 vNext 的 SignalR

c# - .net core 自定义身份验证中的 User.Identity.IsAuthenticated 始终为 false

c# - 序列化类时未标记为可序列化错误

c# - 签署 exe 会使通信变慢吗?

c# - 获取加载程序集的根命名空间(程序集命名空间)