3

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?

5
  • You try changing the Property to Test_Abc? Commented Sep 3, 2019 at 14:15
  • TestAbc and TEST_ABC Are two different names, they have to match Commented Sep 3, 2019 at 14:17
  • @RyanWilson well, I am trying to not do that workaround, as it's not appropriate naming for property in C#. Commented Sep 3, 2019 at 14:17
  • @Train Yes, just looking for any solution allow that mismatch :) Commented Sep 3, 2019 at 14:18
  • 1
    You would need to tell the framework how to deal with the underscore, you could probably used [JsonProperty("TEST_ABC")] attribute for example. Commented Sep 3, 2019 at 14:19

2 Answers 2

7

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

[ConfigurationKeyName("TEST_ABC")]
public string TestAbc { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.