CustomKeyValueAttribute is a C# data annotation for attaching arbitrary JSON key/value pairs to properties or parameters. A companion schema filter reads the attributes and adds the pairs to schemas generated for API inputs, outputs, and complex types. section 11.3.4
Implement the attribute with these conventions:
- Derive from Attribute and expose nullable string Key and Value properties. section 11.3.4
- Use AttributeUsage with Property and Parameter targets. section 11.3.4
- Set AllowMultiple to true so one member can carry several metadata pairs. section 11.3.4
- Register CustomKeyValueFilter through SwaggerGen's SchemaFilter configuration. section 11.3.4
Adding metadata to a property
Applying [CustomKeyValue("x-test-1", "value 1")] and [CustomKeyValue("x-test-2", "value 2")] to UserName produces matching x-test-1 and x-test-2 extensions in the generated LoginDTO schema. Applying the attribute to an endpoint's id parameter similarly adds x-test-3 to that parameter schema. section 11.3.4
Listing 11.7 CustomKeyValueAttribute
namespace MyBGList.Attributes
{
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Parameter,
AllowMultiple = true)]
public class CustomKeyValueAttribute : Attribute
{
public CustomKeyValueAttribute(string? key, string? value)
{
Key = key;
Value = value;
}
public string? Key { get; set; }
public string? Value { get; set; }
}
}
Inspect the complete attribute declaration, including AttributeUsage, the constructor, and Key and Value properties. section 11.3.4
