问题描述
我正在将一个ASP.NET 5 RC1项目迁移到ASP.NET Core,并且遇到了一个我尚未发现或找到解决方案的有趣问题.
I am migrating a ASP.NET 5 RC1 project to ASP.NET Core, and have come across an interesting issue I've not yet seen, or found a solution for.
为了在启动"中使用配置设置,我以前已经通过以下方式检索了配置
In order to use configuration settings within Startup I have previously retrived the configuration the following way
// Works fine for DI both in ASP.NET 5 RC1 and ASP.NET Core
services.Configure<SomeConfigurationClass>(Configuration.GetSection("SomeConfigurationSection"));
// How I previous retrieved the configuration for use in startup.
// No longer available in ASP.NET Core
var someConfigurationToUseLater = Configuration.Get<SomeConfigurationClass>("SomeConfigurationSection");
更新到ASP.NET Core 1.0后,似乎Configuration.Get< T>()不再可用.
After updating to ASP.NET Core 1.0 it seems Configuration.Get<T>() is no longer available.
我尝试更新代码以使用Configuration.GetValue< T>(),但是这似乎不适用于对象,并且仅在提供值的路径时才有效.这样就为我的配置类的 most 提供了一种变通方法,例如
I have tried updating the code to use Configuration.GetValue<T>() however this does not seem to work with objects and will only work when providing a path to a value. This has left me with a workaround for most of my configuration classes like so
var someConfigurationName = "someConfiguration";
var someConfigurationClass = new SomeConfigurationClass()
{
Value1 = Configuration.GetValue<string>($"{someConfigurationName}:value1"),
Foo = Configuration.GetValue<string>($"{someConfigurationName}:foo"),
Bar = Configuration.GetValue<string>($"{someConfigurationName}:bar")
};
但是,当配置类包含对象数组时,这是一个问题.在我的情况下,一组Client对象
However this is an issue when the configuration class contains an array of objects. In my case an array of Client objects
public class ClientConfiguration
{
public Client[] Clients { get; set; }
}
具有以下配置
"configuredClients": {
"clients": [
{
"clientName": "Client1",
"clientId": "Client1"
},
{
"clientName": "Client2",
"clientId": "Client2"
}
]
}
以前该位置绑定到我的配置类的Clients属性没有问题,但我再也找不到在ASP.NET Core 1.0中做到这一点的方法
Where this would previously bind to the Clients property of my configuration class no problem, I can no longer find a way of doing so in ASP.NET Core 1.0
推荐答案
更新后的答案
对于ASP Core 1.1.0,通用模型绑定现在使用Get
:
Updated Answer
For ASP Core 1.1.0 generic model binding is now done using Get
:
var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>();
原始答案
怎么样:
Original Answer
How about this:
var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>();
这篇关于启动中的ASP.NET Core配置部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!