【问题标题】:Variable Substitution in json configuration files for ASP.NET Core?ASP.NET Core 的 json 配置文件中的变量替换?
【发布时间】:2021-03-20 04:56:59
【问题描述】:

我想为我的 ASP.NET Core 项目使用 JSON 配置,如下所述:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2

我的配置是这样调用的:

config
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{commandConfig["Site"]}.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables();

在每个appsettings.<site>.json 中,我都可以这样写:

{
    "Site": "siteName1"
}

但这似乎是一种浪费。我想要的是把这个放在appsettings.json:

{
    "Site": "$(Site)"
}

并有变量替换替换 $(Site) 适当。

这样的事情可能吗?

【问题讨论】:

  • 应该用什么替换$(Site)
  • @DavidG 是的,这种语法中没有任何东西允许这样做,所以我想在最后做点什么,比如.SubstituteVariables(context); 并在上下文映射中传入 Site。
  • 好吧,让我重新表述一下我要去的地方...如果您想用特定的已知值替换,那么您已经知道该值对吗?
  • 是的。但是,如果我有 20 个站点,管理 20 个站点配置文件,这些文件不仅包含它们的 Site 设置,还包含它们的日志位置 (c:\logs\${Site})、它们的错误电子邮件主题 ([${Site}] Error Occurred), etc is painful. Better to specify those three once in the appsettings.json`,正如我在本文中所写评论而不是手动替换和维护 20 个特定于站点的文件。
  • 为什么你有 20 个配置文件?这没有意义。您有一个具有可替换值的配置文件。例如config.EmailSubject.Replace("$(Site)", theNameOfThisSite)

标签: asp.net-core


【解决方案1】:

我为此创建了一个库,它完全符合您的期望。见:https://github.com/molinch/ConfigurationSubstitutor 您只需要将其注册为另一个配置源即可。

例如,如果您在配置中定义了这三个条目:

  • Foo = {Bar1}{Bar2}{Bar1}
  • Bar1 = 咖啡师
  • Bar2 = -Jean-

当从配置中请求 Foo 时,你会得到:Barista-Jean-Barista

【讨论】:

    【解决方案2】:

    我不确定这是否可能。

    我建议使用环境变量:

    var mySiteVariable = Environment.GetEnvironmentVariable("MySiteVariable");
    
    config
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{mySiteVariable}.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();
    

    更新:

    如果您不想使用其他 json 文件,可以使用AddInMemoryCollection。在链中稍后添加的配置将覆盖链中较早的配置中的变量。

    config.SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddInMemoryCollection(new Dictionary<string, string>()
        {
            {"MyConfigVariable", "overwrite with this value"}
        });
    

    没有内置的方法可以做你想做的事。如果您真的愿意,您可以随时自行读取和解析 json 文件。

    【讨论】:

    • 不,这没有抓住重点。我不想在配置文件名中放入替换的内容,我希望替换文件本身中的设置。
    • 就像我说的,我不确定这是否可能。您可以做的最好的事情是通过添加可以由环境变量或其他东西动态确定的新配置来“覆盖”配置设置。它甚至不必是 json(见我的更新)。
    • 是否可以在某处添加一个层来“解释”配置值,以便在运行时替换它们?
    • 我不完全确定你的意思,但在运行时,如果你愿意,你绝对可以用新值重建你的配置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2018-02-13
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多