ASP.NET Core Options pattern with name split by single underscore

我们两清 提交于 2021-01-29 02:57:38

问题


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

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