Skip to content

Commit 71c3316

Browse files
document ConfigurationKeyName (#35274)
1 parent 14ae87d commit 71c3316

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

aspnetcore/fundamentals/configuration/options.md

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Discover how to use the options pattern to represent groups of rela
55
monikerRange: '>= aspnetcore-3.1'
66
ms.author: tdykstra
77
ms.custom: mvc
8-
ms.date: 01/13/2022
8+
ms.date: 04/19/2025
99
uid: fundamentals/configuration/options
1010
---
1111
# Options pattern in ASP.NET Core
@@ -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. 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 the [`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 isn't 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+
The `Title` and `Name` class properties are bound to the `position-title` and `position-name` from the following `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)