.NET控制台应用程序无法读取config.json

awj*_*awj 0 .net c# configuration json configurationmanager

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

我有以下代码:

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)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "Azure": {
    "Storage": {
      "ConnectionString": "...",
      "ContainerName": "..."
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "..."
    }
  },
  "Logging": {
    "RecordProgress": "..."
  }
}
Run Code Online (Sandbox Code Playgroud)

但该config对象不包含任何键.

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

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

Tod*_*odd 5

我原来的答案是不合适的.这是一个更新版本.这是基于最近发布的RC2.

FileNotFoundException如果找不到配置文件,则将抛出当前运行时.该AddJsonFile()扩展方法采用所谓的可选参数optional,如果为true,将导致该方法不扔.

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

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

var config = builder.Build();
Run Code Online (Sandbox Code Playgroud)

最后,config["Key"]索引器对我不起作用.相反,我不得不使用GetSection()扩展方法.因此,上面的示例配置文件可能会被访问​​:

// var result = config["Logging"];
var section = config.GetSection("Logging");
var result = section["RecordProgress"];
Run Code Online (Sandbox Code Playgroud)

我暂时离开了旧答案.

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

引用该问题.

感谢repro项目.看起来您需要更新project.json文件以获得"content"节点并在此处指定Config.json.

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

看来您的内容可能需要新的内容元素project.json.

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