2016-04-27 42 views
0

在構建使用新的ConfigurationBuilder實現的以前爲appSettings的.NET控制檯應用程序時,我遇到了問題。.NET控制檯應用程序不讀取config.json

我有以下代碼:

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文件可以找到,爲什麼設置沒有被加載?

回答

5

我原來的答案不合格。這是一個更新版本。這是基於最近發佈的RC2。

如果找不到配置文件,當前運行時將丟棄FileNotFoundExceptionAddJsonFile()擴展方法使用一個名爲optional的可選參數,如果爲true,將導致方法不拋出。

我加了config.json,它沒有被複制到bin目錄,所以我不得不使用SetBasePath()擴展方法指定位置。這是Web項目模板在啓動時使用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

引用此問題。

感謝您的repro項目。看起來您需要更新 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" ], ...

+0

感謝您的建議@Todd但都沒有效果,當我嘗試過。 – awj

相關問題