Reputation: 39190
I noticed that the following statement produces a discrepancy.
public static string GetValidation(this IConfiguration self, string key)
{
IConfigurationSection section = self.GetSection(key);
string value1 = section.Value;
string value2 = section.GetValue<string>(key);
return "";
}
The corresponding section in the config has correctly set value and is correctly located using the specified path.
...
"SomePath": "Some value",
"AlsoTried": 13,
"AndEven": true,
...
The first value is as expected, the content of the node. The second is null. When I tried typing to integers and booleans, I got zero and falsity, i.e. defaults (of course I changed the value in the config file to non-string, e.g. 13 and true respectively.
I've scrutinized the docs and googled the issue, coming up with nothing useful.
What am I missing here (because I'm sure like a rat's behind it's not a bug in .NET, hehe)?
Upvotes: 0
Views: 893
Reputation: 8662
I'm going to assume you are passing test:SomeValue
as your key and you configuration looks like:
"test": {
"SomePath": "Some value",
"AlsoTried": 13,
"AndEven": true
}
Your call to self.GetSection(key);
is returning the specific value you have asked for e.g.
var section = self.GetSection("test:SomePath");
This means section
is now the "value" of that path e.g. Some value
, which is why the section.Value
property returns the correct data. But when you call section.GetValue<string>("test:SomePath")
or just section.GetValue<string>("SomePath")
then section does not contain a KeyValuePair for "SomePath", so you get null.
If you call GetValue<string>(key)
on self
it will return the correct value:
var section = self.GetValue<string>(key);
Upvotes: 2
Reputation: 11364
the values in your configuration should be all strings. Use GetValue to convert them to their proper formats. Configuration is supposed to be a dictionary of < string Key, string Value>.
"SomePath": "Some value",
"AlsoTried": "13",
"AndEven": "true",
with the following commands, you should get the proper values and their types
section.GetValue<int>("AlsoTried"); // out type will int and value 13.
section.GetValue<bool>("AndEven"); // out type will be bool and value true
hope it helps.
Found this URL that explains about Configuration and data retrieval as well. Good read.
Upvotes: 0