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

1.9k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

Starting with .NET 6.0 Preview 7 you can use ConfigurationKeyNameAttribute class.

[ConfigurationKeyName("TEST_ABC")]
public string TestAbc { get; set; }