在.NetCore中,这就是我所做的:
正常设置:
在您的appsettings.json中,为您的自定义定义创建一个配置部分:
"IDP": [
{
"Server": "asdfsd",
"Authority": "asdfasd",
"Audience": "asdfadf"
},
{
"Server": "aaaaaa",
"Authority": "aaaaaa",
"Audience": "aaaa"
}
]
创建一个类来对对象建模:
public class IDP
{
public String Server { get; set; }
public String Authority { get; set; }
public String Audience { get; set; }
}
在您的启动-> ConfigureServices中
services.Configure<List<IDP>>(Configuration.GetSection("IDP"));
注意:如果需要立即在ConfigureServices方法中访问列表,则可以使用...
var subSettings = Configuration.GetSection("IDP").Get<List<IDP>>();
然后在您的控制器中,如下所示:
Public class AccountController: Controller
{
private readonly IOptions<List<IDP>> _IDPs;
public AccountController(IOptions<List<Defined>> IDPs)
{
_IDPs = IDPs;
}
...
}
就像一个例子,我在上面的控制器中的其他地方使用了它,如下所示:
_IDPs.Value.ForEach(x => {
});
边缘盒
如果您需要多个配置,但是它们不能位于一个数组中,并且您不知道一次一次会有多少个子设置。使用以下方法。
appsettings.json
"IDP": {
"0": {
"Description": "idp01_test",
"IDPServer": "https://intapi.somedomain.com/testing/idp01/v1.0",
"IDPClient": "someapi",
"Format": "IDP"
},
"1": {
"Description": "idpb2c_test",
"IDPServer": "https://intapi.somedomain.com/testing/idpb2c",
"IDPClient": "api1",
"Format": "IDP"
},
"2": {
"Description": "MyApp",
"Instance": "https://sts.windows.net/",
"ClientId": "https://somedomain.com/12345678-5191-1111-bcdf-782d958de2b3",
"Domain": "somedomain.com",
"TenantId": "87654321-a10f-499f-9b5f-6de6ef439787",
"Format": "AzureAD"
}
}
模型
public class IDP
{
public String Description { get; set; }
public String IDPServer { get; set; }
public String IDPClient { get; set; }
public String Format { get; set; }
public String Instance { get; set; }
public String ClientId { get; set; }
public String Domain { get; set; }
public String TenantId { get; set; }
}
为Expando对象创建扩展
public static class ExpandObjectExtension
{
public static TObject ToObject<TObject>(this IDictionary<string, object> someSource, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
where TObject : class, new()
{
Contract.Requires(someSource != null);
TObject targetObject = new TObject();
Type targetObjectType = typeof(TObject);
foreach (PropertyInfo property in
targetObjectType.GetProperties(bindingFlags))
{
if (someSource.ContainsKey(property.Name)
&& property.PropertyType == someSource[property.Name].GetType())
{
property.SetValue(targetObject, someSource[property.Name]);
}
}
return targetObject;
}
}
配置服务
var subSettings = Configuration.GetSection("IDP").Get<List<ExpandoObject>>();
var idx = 0;
foreach (var pair in subSettings)
{
IDP scheme = ((ExpandoObject)pair).ToObject<IDP>();
if (scheme.Format == "AzureAD")
{
var section = $"IDP:{idx.ToString()}";
services.AddProtectedWebApi(Configuration, section, scheme.Description);
}
idx++;
}