Skip to content

Commit 0094967

Browse files
committed
document ConfigurationKeyName
1 parent 14ae87d commit 0094967

3 files changed

Lines changed: 37 additions & 0 deletions

File tree

aspnetcore/fundamentals/configuration/options.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,22 @@ In the preceding code, by default, changes to the JSON configuration file after
108108

109109
<a name="named"></a>
110110

111+
## Specify a custom key name for a configuration property using ConfigurationKeyName
112+
113+
By default, the property names of the Options class are used as the key name in the configuration source. For example, if the property name is `Title`, the key name in the configuration is `Title` as well.
114+
115+
When the names differentiate, you can use [`ConfigurationKeyName` attribute](xref:Microsoft.Extensions.Configuration.ConfigurationKeyNameAttribute) to specify the key name in the configuration source. Using this technique, you can map a property in the configuration to one in your code with a different name.
116+
117+
This is useful when the property name in the configuration source is not a valid C# identifier, or when you want to use a different name in your code.
118+
119+
For example, consider the following Options class:
120+
121+
:::code language="csharp" source="~/fundamentals/configuration/options/samples/6.x/OptionsSample/Models/PositionOptionsWithConfigurationKeyName.cs" id="snippet":::
122+
123+
With the following `appsettings.json`, the `Title` and `Name` class properties are bound to the `position-title` and `position-name` from the `appsettings.json` file:
124+
125+
:::code language="json" source="~/fundamentals/configuration/options/samples/6.x/OptionsSample/appsettings.KN.json":::
126+
111127
## Named options support using IConfigureNamedOptions
112128

113129
Named options:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
namespace SampleApp.Models
2+
{
3+
#region snippet
4+
public class PositionOptionsWithConfigurationKeyName
5+
{
6+
public const string Position = "Position";
7+
8+
[ConfigurationKeyName("position-title")]
9+
public string Title { get; set; } = String.Empty;
10+
11+
[ConfigurationKeyName("position-name")]
12+
public string Name { get; set; } = String.Empty;
13+
}
14+
#endregion
15+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"Position": {
3+
"position-title": "Editor",
4+
"position-name": "Joe Smith"
5+
}
6+
}

0 commit comments

Comments
 (0)