Config.GetSection<T> with invalid class property names

242 views Asked by At

Using IConfigurationRoot extension method

public static T GetSectionAsObject<T>(this IConfigurationRoot configuration, string key)
{
    return configuration.GetSection(key).Get<T>();
}

I am retrieving sections from configuration file as objects. For example I have a section in configuration file:

"RandomClass": {
    "Attribute1": "x",
    "Attribute2": "y",
    "Attribute3": "z"
  },

which gets mapped to an object of class RandomClassSettings

public class RandomClassSettings
    {
        public string Attribute1 { get; set; }
        public string Attribute2 { get; set; }
        public string Attribute3 { get; set; }
    }

This works.

Unfortunately, in the configuration file I have another section with a key "attribue.RandomAttribue" which won't get mapped to object like in the previous example because of the "." in it's name. Any ideas how to make it possible? I can't rename the key in configuration file.

I tried making another class Attribute and having a class like below, but it doesn't work either.

public class NewClassSettings {
        public Attribute attribute { get; set; }
    }

Edit: I am using .NET Framework 4.7.2

1

There are 1 answers

2
pfx On

Data from appsettings.json doesn't get JSON deserialized, a custom JsonConfigurationFileParser takes care of the parsing. Any System.Text.Json nor Json.NET attributes are not being considered.

Here, you'll need to apply a ConfigurationKeyNameAttribute on the property of the class representing that data.

Suppose your data looks like below with that mentioned attribue.RandomAttribue key.

{
    "data": {
        "attribue.RandomAttribue": "abc"
    }
}

Then your class will need to look like this - you can give the property with the ConfigurationKeyNameAttribute any name of your choice.

public class Data
{
    [ConfigurationKeyName("attribue.RandomAttribue")]
    public string Item { get; set; }
}

You get that data with below call.

var data = configuration.GetSection("data").Get<Data>();
Console.WriteLine(data.Item); // abc