liveBook · Manning

CustomKeyValueAttribute

As explained in Building Web APIs with ASP.NET Core

CustomKeyValueAttribute is a book-specific C# attribute that associates arbitrary JSON keys and values with properties or parameters.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Defines the attribute and filter integration, then verifies generated swagger.json output; it does not develop broader metadata processing.
Examples
Uses LoginDTO properties, repeated x-test metadata, an endpoint id parameter, and corresponding swagger.json schemas.
What it assumes
Assumes basic C# attributes and API documentation configuration while teaching AttributeUsage and schema-filter registration.
What you can do after
Apply it via SwaggerGen configuration to emit custom JSON extensions on annotated API schemas.
How it connects
Connects C# attributes, AttributeUsage, ISchemaFilter, SwaggerGen, OpenAPI schemas, and JSON schema extensions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.