C#C
C#2y ago
voltagex

✅ NotSupportedException: JsonTypeInfo metadata for type... & "minimal" APIs

Coming back to C# after quite a while and minimal APIs got complicated.
What's going on with the error here? What does it actually want me to add?

Why is it trying to serialize a System.Func?
NotSupportedException: JsonTypeInfo metadata for type 'System.Func`2[Microsoft.Extensions.Options.IOptions`1[filelistclient.FileLocationOptions],System.String]' was not provided by TypeInfoResolver of type '[filelistclient.UnneededAddedComplexityJsonContext]'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.

System.Text.Json.ThrowHelper.ThrowNotSupportedException_NoMetadataForType(Type type, IJsonTypeInfoResolver resolver)


    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateSlimBuilder(args);

            builder.Services.ConfigureHttpJsonOptions(options =>
                options.SerializerOptions.TypeInfoResolverChain.Insert(0, UnneededAddedComplexityJsonContext.Default));
            builder.Services.AddOptions<FileLocationOptions>().BindConfiguration("FileLocation");
            var app = builder.Build();


            var testApi = app.MapGroup("/options");
            testApi.MapGet("/", () => GetOptions);
            app.Run();
        }

        private static string GetOptions(IOptions<FileLocationOptions> options)
        {
            return $"{options.Value.PathToScan}, {options.Value.SaveScanToPath}";
        }
    }


namespace filelistclient
{
    [JsonSourceGenerationOptions(WriteIndented = true)]
    [JsonSerializable(typeof(FileLocationOptions))]
    [JsonSerializable(typeof(IOptions<FileLocationOptions>))]
    internal partial class UnneededAddedComplexityJsonContext : JsonSerializerContext
    {
    }
}
Was this page helpful?