How to get string array from core console appSettings.json file

风流意气都作罢 提交于 2020-05-15 08:47:25

问题


How do I return an string[] from the IConfigurationRoot object?

File exists and is set to copy to output

Code

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("settings.json", optional: false, reloadOnChange: false);
_configuration = builder.Build();

var arr = _configuration["stringArray"]; // this returns null
var arr1 = _configuration["stringArray:0"]; // this works and returns first element

Settings.json

{
  "stringArray": [
    "myString1",
    "myString2",
    "myString3"
  ]
}

回答1:


Use the GetValue<TResult> extension to get the value of the section.

// Requires NuGet package "Microsoft.Extensions.Configuration.Binder"
var array = _configuration.GetValue<string[]>("stringArray");

Or try binding to the section

var values = new List<string>();
_configuration.Bind("stringArray", values);

Alternatively ConfigurationBinder.Get<T> syntax can also be used, which results in more compact code:

List<string values = _configuration.GetSection("stringArray").Get<string[]>();

Reference Configuration in ASP.NET Core: Bind to an object graph



来源:https://stackoverflow.com/questions/50727404/how-to-get-string-array-from-core-console-appsettings-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!