Search code examples
asp.net-coregraphqlhotchocolate

How can you control the serialization of Enum values in HotChocolate?


HotChocolate serializes enum values in all upper snail case, which leads to being the enum value FooBar being inferred as FOO_BAR by Hot Chocolate, but value.ToString() and Enum.GetName(value) gives FooBar, and Hot Chocolate seems to ignore [EnumMember(Value = "FooBar")].

How can I change the serialization to any way I'd like?


Solution

  • HotChocolate server v11 follows the spec recommendation which defaults to enum values being serialized as UPPER_SNAIL_CASE per default.

    You can change this like this:

        builder
            .AddConvention<INamingConventions>(new YourNamingConvention())
    
    
        public class YourNamingConvention
            : DefaultNamingConventions
        {
            public override NameString GetEnumValueName(object value)
            {
                if (value == null)
                {
                    throw new ArgumentNullException(nameof(value));
                }
                return value.ToString().ToUpperInvariant(); // change this to whatever you like
            }
        }