2

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

chuftica
  • 160
  • 8

1 Answers1

4

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
pfx
  • 20,323
  • 43
  • 37
  • 57
  • Thanks for the solution! Unfortunately, I forgot to mention that I'm developing on .NET Framework 4.7.2, not .NET Core. – chuftica Mar 27 '23 at 08:01
  • @chuftica You'll need to reference [`Microsoft.Extensions.Configuration.Abstractions`](https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Abstractions/7.0.0#supportedframeworks-body-tab) with support for `.NET Framework`. – pfx Mar 27 '23 at 10:07