【问题标题】:Overriding Configuration Values in config.json file in Azure Web App in ASP.Net 5在 ASP.Net 5 中的 Azure Web App 中覆盖 config.json 文件中的配置值
【发布时间】:2016-02-24 15:07:08
【问题描述】:

我有一个 ASP.Net 5 应用程序,其中一些配置值存储在 config.json 文件中。我的 config.json 文件是这样的。

{
  "AppSettings": {
    "SiteEmailAddress": "some@email.com",
    "APIKey": "some_api_key"
  }
}

我正在设置 config.json 文件以在 Startup.cs 这样的文件中使用。

public static IConfigurationRoot Configuration;

public Startup(IApplicationEnvironment appEnv) {

    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
    Configuration = builder.Build();
}

并像这样访问配置设置..

var email = Startup.Configuration["AppSettings:SiteEmailAddress"];

在 ASP.Net 的早期版本中,我们可以使用 Web.Config 文件来存储这些应用程序设置,并在 Azure 应用程序设置部分的应用程序设置中覆盖它们,这样就不会出现任何问题。但是我怎样才能在 ASP.Net 5 应用程序中做同样的事情。

如何在 Azure 的应用设置部分覆盖 config.json 文件中的配置值。

【问题讨论】:

    标签: c# asp.net azure asp.net-core


    【解决方案1】:

    就像您习惯的那样,将它们添加为 Azure 中的应用程序设置。 对于嵌套的配置值,使用

    AppSettings:SiteEmailAddress
    

    等等……(这里的AppSettings指的是你在config.json中使用的,与Azure App Settings相似纯属巧合)

    AddEnvironmentVariables() 需要像您所做的那样才能工作。

    【讨论】:

    • 在 .NET Core 中也称为 appsettings.json
    【解决方案2】:

    假设你有appsettings.json,你可以添加另一个文件appsettings.{Environment}.json,即appsettings.Production.json。只有在生产文件中定义的设置才会覆盖 appsettings.json 中的设置。 现在,将以下内容添加到 Startup 的构造函数中

    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);
    

    接下来,您应该转到定义了所有服务器的 launchSettings.json 并将环境变量更新为 Production。例如,

    "web": {
      "commandName": "web",
      "environmentVariables": {
        "Hosting:Environment": "Production"
      }
    

    现在部署到 azure。

    【讨论】:

    • 有没有办法不必在每次部署时都更改 Hosting:Environment?我们可以把它永久化吗?
    • 您应该在 launchSettings.json 文件中为每个环境定义“配置文件”。每个配置文件都应该有它自己的“Hosting:Environment”。即对于 IIS Express => 开发,对于 web => 生产
    • 我明白了。但是 Azure 如何知道选择“网络”配置文件?如果我想要一个“Azure 生产”配置文件怎么办?
    • 可能是在VS的msbuild脚本中定义的。您需要查找如何编辑它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2018-11-29
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多