【问题标题】:.NET console app not reading config.json.NET 控制台应用程序未读取 config.json
【发布时间】:2016-08-21 13:57:23
【问题描述】:

在构建一个使用新的 ConfigurationBuilder 实现的 .net 控制台应用程序时,我遇到了一个问题。

我有以下代码:

public static void Main(string[] args)
{
    try
    {
        var builder = new ConfigurationBuilder().AddJsonFile("config.json");
        var config = builder.Build();

        if (config["Azure"] != null)
        {
            ;
        }
    }
    catch (System.IO.FileNotFoundException exception)
    {
        ...
    }
}

config.json 文件位于同一目录中,如下所示:

{
  "Azure": {
    "Storage": {
      "ConnectionString": "...",
      "ContainerName": "..."
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "..."
    }
  },
  "Logging": {
    "RecordProgress": "..."
  }
}

但是config 对象不包含键。

我在某处读到,如果无法找到传递给 AddJsonFile 的文件路径,那么它会抛出 FileNotFoundException,但在我的代码中永远不会抛出异常。

那么假设config.json文件可以找到,为什么没有加载设置?

【问题讨论】:

    标签: c# .net json configuration configurationmanager


    【解决方案1】:

    我原来的答案是错误的。这是一个更新的版本。这是基于最近发布的 RC2。

    如果找不到配置文件,当前运行时将抛出FileNotFoundExceptionAddJsonFile() 扩展方法接受一个名为 optional 的可选参数,如果为真,将导致方法不抛出。

    我添加了config.json,但它没有被复制到bin目录,所以我必须使用SetBasePath()扩展方法指定位置。这就是 Web 项目模板在 Startup 中所做的,使用 IHostingEnvironment.ContentRootPath。在控制台应用中,您可以使用Directory.GetCurrentDirectory()

    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("config.json");
    
    var config = builder.Build();
    

    最后,config["Key"] 索引器对我不起作用。相反,我不得不使用GetSection() 扩展方法。所以你上面的示例配置文件可以通过以下方式访问:

    // var result = config["Logging"];
    var section = config.GetSection("Logging");
    var result = section["RecordProgress"];
    

    我暂时留下了旧答案。

    旧答案: 我在这里找到了一个可能的解决方案:https://github.com/aspnet/Mvc/issues/4481

    引用问题。

    感谢您的复制项目。看起来你需要更新 project.json 文件具有“内容”节点并具有 Config.json 此处指定。

    示例: https://github.com/aspnet/MusicStore/blob/dev/src/MusicStore/project.json#L22

    您的project.json 中似乎需要一个新的内容元素。

    ... "content": [ "Areas", "Views", "wwwroot", "config.json", "web.config" ], ...

    【讨论】:

    • 感谢@Todd 的建议,但我尝试后没有效果。
    【解决方案2】:

    我遇到了同样的问题。

    config.json 位于正确的目录中,但仍未找到。

    解决办法: config.json 包含破坏 json 语法的错字。修复 config.json 中的 json 语法/格式后,一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2022-08-02
      • 2022-12-12
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多