2016-12-26 143 views
16

JSON數組在appsettings.jsonASP .NET核心獲取使用IConfiguration

{ 
     "MyArray": [ 
      "str1", 
      "str2", 
      "str3" 
     ] 
} 

在Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddSingleton<IConfiguration>(Configuration); 
} 

在HomeController的

public class HomeController : Controller 
{ 
    private readonly IConfiguration _config; 
    public HomeController(IConfiguration config) 
    { 
     this._config = config; 
    } 

    public IActionResult Index() 
    { 
     return Json(_config.GetSection("MyArray")); 
    } 
} 

上面有我的代碼,我得到空 如何獲得數組?

回答

18

如果你想選擇第一項的值,那麼你應該做的像這個 -

var item0 = _config.GetSection("MyArray:0"); 

如果你想選擇整個陣列的值,那麼你應該做的像這個 -

IConfigurationSection myArraySection = _config.GetSection("MyArray"); 
var itemArray = myArraySection.AsEnumerable(); 

理想情況下,您應該考慮使用官方文檔建議的options pattern。這會給你更多的好處。

7

在appsettings.json添加一個級別:

{ 
    "MySettings" 
     "MyArray": [ 
      "str1", 
      "str2", 
      "str3" 
     ] 
    } 
} 

創建一個類代表您的部分:

public class MySettings 
{ 
    public List<string> MyArray {get; set;} 
} 

在應用程序啓動類,綁定你的模型在DI服務注入它:

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options)); 

並且在您的控制器中,從DI服務獲取配置數據:

public class HomeController : Controller 
{ 
    private readonly List<string> _myArray; 

    public HomeController(IOptions<MySettings> mySettings) 
    { 
     _myArray = mySettings.Value.MyArray; 
    } 

    public IActionResult Index() 
    { 
     return Json(_myArray); 
    } 
} 

您也可以存儲在屬性整個配置模型在你的控制器,如果你需要的所有數據:

public class HomeController : Controller 
{ 
    private readonly MySettings _mySettings; 

    public HomeController(IOptions<MySettings> mySettings) 
    { 
     _mySettings = mySettings.Value; 
    } 

    public IActionResult Index() 
    { 
     return Json(_mySettings.MyArray); 
    } 
} 

的ASP。NET核心的依賴注入服務的工作就像一個魅力:)

7

如果您有複雜的JSON對象的數組是這樣的:

{ 
    "MySettings": { 
    "MyValues": [ 
     { "Key": "Key1", "Value": "Value1" }, 
     { "Key": "Key2", "Value": "Value2" } 
    ] 
    } 
} 

您可以檢索的設置是這樣的:

var valuesSection = configuration.GetSection("MySettings:MyValues"); 
foreach (IConfigurationSection section in valuesSection.GetChildren()) 
{ 
    var key = section.GetValue<string>("Key"); 
    var value = section.GetValue<string>("Value"); 
} 
0

你可以直接獲取陣列而不增加配置中的新層次:

public void ConfigureServices(IServiceCollection services) { 
    services.Configure<List<String>>(Configuration.GetSection("MyArray")); 
    //... 
} 
12

你可以在攤主以下兩個包的NuGet:

Microsoft.Extensions.Configuration  
Microsoft.Extensions.Configuration.Binder 

然後,你將不得不使用下面的擴展方法的可能性:

var myArray = _config.GetSection("MyArray").Get<string[]>();