问题
I am trying to load my app settings with ASP.NET Core Options pattern.
The appsettings.json
contains:
{
"TEst": "hello",
"TEST_ABC": "2"
}
POCO class:
public class AppSetting
{
public string Test { get; set; }
public string TestAbc { get; set; }
}
Bind to configuration:
services.Configure<AppSetting>(Configuration);
While access AppSetting instance in controller, I can only get config Test
as hello
. TestAbc
is set to null
.
It seems Options pattern couldn't convert this kind of naming configuration, is it possible by any other means to achieve this?
回答1:
The only way to have it done automatically would be to name your property with the underscore (Test_Abc
). Short of that, you can specify the mapping manually:
services.Configure<AppSettings>(o =>
{
o.TestAbc = Configuration["TEST_ABC"];
// etc.
});
@DavidG's comment about using [JsonProperty]
may work. I've never tried that in the context of configuration. However, it will only work, if it works at all, when using the JSON config provider. If you later need to satisfy this via an environment variable, for example, you're out of luck. As such, I would stick with a more universally applicable solution than that.
来源:https://stackoverflow.com/questions/57773515/asp-net-core-options-pattern-with-name-split-by-single-underscore