Gar*_*ary 127 c# asp.net-core-mvc asp.net-core
在appsettings.json中
{
"MyArray": [
"str1",
"str2",
"str3"
]
}
Run Code Online (Sandbox Code Playgroud)
在Startup.cs中
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)
在HomeController中
public class HomeController : Controller
{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
this._config = config;
}
public IActionResult Index()
{
return Json(_config.GetSection("MyArray"));
}
}
Run Code Online (Sandbox Code Playgroud)
上面有我的代码,我得到null如何获取数组?
Raz*_*tru 215
您可以安装以下两个NuGet包:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用以下扩展方法:
var myArray = _config.GetSection("MyArray").Get<string[]>();
Run Code Online (Sandbox Code Playgroud)
San*_*ket 75
如果你想选择第一项的价值,你应该这样做 -
var item0 = _config.GetSection("MyArray:0");
Run Code Online (Sandbox Code Playgroud)
如果你想挑选整个阵列的价值,你应该这样做 -
IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();
Run Code Online (Sandbox Code Playgroud)
理想情况下,您应该考虑使用官方文档建议的选项模式.这将为您带来更多好处.
Adr*_*ris 51
在appsettings.json中添加一个级别:
{
"MySettings": {
"MyArray": [
"str1",
"str2",
"str3"
]
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个代表您的部分的类:
public class MySettings
{
public List<string> MyArray {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
在您的应用程序启动类中,绑定您的模型并将其注入DI服务:
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
Run Code Online (Sandbox Code Playgroud)
在您的控制器中,从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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果需要所有数据,还可以将整个配置模型存储在控制器的属性中:
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptions<MySettings> mySettings)
{
_mySettings = mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.MyArray);
}
}
Run Code Online (Sandbox Code Playgroud)
ASP.NET Core的依赖注入服务就像一个魅力:)
Dmi*_*lov 26
如果你有这样的复杂JSON对象数组:
{
"MySettings": {
"MyValues": [
{ "Key": "Key1", "Value": "Value1" },
{ "Key": "Key2", "Value": "Value2" }
]
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式检索设置:
var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
var key = section.GetValue<string>("Key");
var value = section.GetValue<string>("Value");
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*ief 21
这对我来说可以从我的配置中返回一个字符串数组:
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
.Get<string[]>();
Run Code Online (Sandbox Code Playgroud)
我的配置部分如下所示:
"AppSettings": {
"CORS-Settings": {
"Allow-Origins": [ "http://localhost:8000" ],
"Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
}
}
Run Code Online (Sandbox Code Playgroud)
Bja*_*i B 11
点网核心 3.1:
json配置:
"TestUsers":
{
"User": [
{
"UserName": "TestUser",
"Email": "Test@place.com",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "Test2@place.com",
"Password": "P@ssw0rd!"
}]
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个 User.cs 类,该类具有与上面 Json 配置中的 User 对象相对应的自动属性。然后您可以参考 Microsoft.Extensions.Configuration.Abstractions 并执行以下操作:
List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();
Run Code Online (Sandbox Code Playgroud)
jay*_*cer 10
对于从配置中返回复杂的JSON对象数组的情况,我调整了@djangojazz的答案以使用匿名类型和动态而不是元组。
给定设置部分:
"TestUsers": [
{
"UserName": "TestUser",
"Email": "Test@place.com",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "Test2@place.com",
"Password": "P@ssw0rd!"
}],
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方式返回对象数组:
public dynamic GetTestUsers()
{
var testUsers = Configuration.GetSection("TestUsers")
.GetChildren()
.ToList()
.Select(x => new {
UserName = x.GetValue<string>("UserName"),
Email = x.GetValue<string>("Email"),
Password = x.GetValue<string>("Password")
});
return new { Data = testUsers };
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以直接获取数组,而无需在配置中增加新级别:
public void ConfigureServices(IServiceCollection services) {
services.Configure<List<String>>(Configuration.GetSection("MyArray"));
//...
}
Run Code Online (Sandbox Code Playgroud)
有点老问题了,但是我可以为使用C#7标准的.NET Core 2.1提供更新的答案。说我仅在appsettings.Development.json中有一个列表,例如:
"TestUsers": [
{
"UserName": "TestUser",
"Email": "Test@place.com",
"Password": "P@ssw0rd!"
},
{
"UserName": "TestUser2",
"Email": "Test2@place.com",
"Password": "P@ssw0rd!"
}
Run Code Online (Sandbox Code Playgroud)
],
我可以将它们提取到实现并连接了Microsoft.Extensions.Configuration.IConfiguration的任何位置,如下所示:
var testUsers = Configuration.GetSection("TestUsers")
.GetChildren()
.ToList()
//Named tuple returns, new in C# 7
.Select(x =>
(
x.GetValue<string>("UserName"),
x.GetValue<string>("Email"),
x.GetValue<string>("Password")
)
)
.ToList<(string UserName, string Email, string Password)>();
Run Code Online (Sandbox Code Playgroud)
现在,我有一个类型正确的对象的列表。如果我进入testUsers.First(),Visual Studio现在应该显示“用户名”,“电子邮件”和“密码”的选项。
这对我有用;创建一些json文件:
{
"keyGroups": [
{
"Name": "group1",
"keys": [
"user3",
"user4"
]
},
{
"Name": "feature2And3",
"keys": [
"user3",
"user4"
]
},
{
"Name": "feature5Group",
"keys": [
"user5"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
然后,定义一些映射的类:
public class KeyGroup
{
public string name { get; set; }
public List<String> keys { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
nuget 包:
Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3
Run Code Online (Sandbox Code Playgroud)
然后,加载它:
using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Collections.Generic;
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);
IConfigurationRoot config = configurationBuilder.Build();
var sectionKeyGroups =
config.GetSection("keyGroups");
List<KeyGroup> keyGroups =
sectionKeyGroups.Get<List<KeyGroup>>();
Dictionary<String, KeyGroup> dict =
keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);
Run Code Online (Sandbox Code Playgroud)
简写:
var myArray= configuration.GetSection("MyArray")
.AsEnumerable()
.Where(p => p.Value != null)
.Select(p => p.Value)
.ToArray();
Run Code Online (Sandbox Code Playgroud)
它返回一个字符串数组:
{"str1","str2","str3"}
在ASP.NET Core 2.2和更高版本中,我们可以像您的情况一样在应用程序中的任何位置注入IConfiguration,您可以在HomeController中注入IConfiguration并以此方式获取数组。
string[] array = _config.GetSection("MyArray").Get<string[]>();
Run Code Online (Sandbox Code Playgroud)
Microsoft.Extensions.Configuration.Binder您可以像这样使用包:
在你的appsettings.json
{
"MyArray": [
"str1",
"str2",
"str3"
]
}
Run Code Online (Sandbox Code Playgroud)
创建对象来保存您的配置:
public class MyConfig
{
public List<string> MyArray { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在你的控制器中Bind配置:
public class HomeController : Controller
{
private readonly IConfiguration _config;
private readonly MyConfig _myConfig = new MyConfig();
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
return Json(_config.Bind(_myConfig));
}
}
Run Code Online (Sandbox Code Playgroud)