ASP.NET Core single-file application with default serialization causing error

22 hours ago 1
ARTICLE AD BOX

I'm trying to migrate a simple app with a basic API to crunch numbers to generate a load, to a single-file application as a proof of concept.

generate-load-server.cs:

#! /usr/bin/env dotnet run #:sdk Microsoft.NET.Sdk.Web using Microsoft.AspNetCore.Mvc; using System.Numerics; var builder = WebApplication.CreateBuilder(); builder.Services.AddRequestTimeouts(); var app = builder.Build(); app.UseRequestTimeouts(); app.MapGet("/api/generate-load", ([FromQuery] int? n = default) => { var iterations = n ?? 100000000; ArgumentOutOfRangeException.ThrowIfNegative(iterations); if (Vector.IsHardwareAccelerated) return CalculatePi.MonteCarloVector(iterations); return CalculatePi.MonteCarloBasic(iterations); }).WithRequestTimeout(TimeSpan.FromMinutes(10)); await app.RunAsync("http://localhost:8123"); static class CalculatePi { // implementations... public static decimal MonteCarloBasic(int iter, int? seed = default) { // ... } public static decimal MonteCarloVector(int iter, int? seed = default) { // ... } }

The application starts up fine, but when I call the API, I run into a weird JSON serialization error, completely unrelated to my code.

$ dotnet run generate-load-server.cs info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:8123 info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down. info: Microsoft.Hosting.Lifetime[0] Hosting environment: Production info: Microsoft.Hosting.Lifetime[0] Content root path: S:\test info: Microsoft.AspNetCore.Hosting.Diagnostics[1] Request starting HTTP/1.1 GET http://localhost:8123/api/generate-load?n=1000000000 - - - bunch of requests... info: Microsoft.AspNetCore.Hosting.Diagnostics[1] Request starting HTTP/1.1 GET http://localhost:8123/api/generate-load?n=1000000000 - - - fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HNKN8P5M7SO1", Request id "0HNKN8P5M7SO1:00000001": An unhandled exception was thrown by the application. System.NotSupportedException: JsonTypeInfo metadata for type 'System.Decimal' was not provided by TypeInfoResolver of type '[]'. 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. at System.Text.Json.ThrowHelper.ThrowNotSupportedException_NoMetadataForType(Type type, IJsonTypeInfoResolver resolver) at System.Text.Json.JsonSerializerOptions.GetTypeInfoInternal(Type type, Boolean ensureConfigured, Nullable`1 ensureNotNull, Boolean resolveIfMutable, Boolean fallBackToNearestAncestorType) at System.Text.Json.JsonSerializerOptions.GetTypeInfo(Type type) at Microsoft.AspNetCore.Http.Generated.<GeneratedRouteBuilderExtensions_g>F6DE0C89F6F8484B82B89F44B1C0701B89E2552B502F347FA7B76C4935F008AA9__GeneratedRouteBuilderExtensionsCore.<>c.<MapGet0>b__2_1(Delegate del, RequestDelegateFactoryOptions options, RequestDelegateMetadataResult inferredMetadataResult) in C:\Users\jeff.mercado\AppData\Local\Temp\dotnet\runfile\generate-load-server-165da69c96b0c4ee5a200ebe536be4b7bab40e25dcdf29f15f61d54c4d7f526c\obj\debug\Microsoft.AspNetCore.Http.RequestDelegateGenerator\Microsoft.AspNetCore.Http.RequestDelegateGenerator.RequestDelegateGenerator\GeneratedRouteBuilderExtensions.g.cs:line 92 at Microsoft.AspNetCore.Routing.RouteEndpointDataSource.CreateRouteEndpointBuilder(RouteEntry entry, RoutePattern groupPrefix, IReadOnlyList`1 groupConventions, IReadOnlyList`1 groupFinallyConventions) at Microsoft.AspNetCore.Routing.RouteEndpointDataSource.get_Endpoints() at Microsoft.AspNetCore.Routing.CompositeEndpointDataSource.CreateEndpointsUnsynchronized() at Microsoft.AspNetCore.Routing.CompositeEndpointDataSource.EnsureEndpointsInitialized() at Microsoft.AspNetCore.Routing.CompositeEndpointDataSource.get_Endpoints() at Microsoft.AspNetCore.Routing.DataSourceDependentCache`1.Initialize() at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) at Microsoft.AspNetCore.Routing.Matching.DataSourceDependentMatcher..ctor(EndpointDataSource dataSource, Lifetime lifetime, Func`1 matcherBuilderFactory) at Microsoft.AspNetCore.Routing.Matching.DfaMatcherFactory.CreateMatcher(EndpointDataSource dataSource) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.InitializeCoreAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|10_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|10_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|10_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task`1 matcherTask) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application) bunch of this error...

System.NotSupportedException: JsonTypeInfo metadata for type 'System.Decimal' was not provided by TypeInfoResolver of type '[]'. 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.

So it suddenly doesn't know how to serialize decimals?

The same code ran fine no issues when run in LINQPad, but for some reason there's an issue with the serializer config. Do I need to add additional references/configuration? Why would I need to redefine the serialization for the builtin decimal?

I have the .NET 11 preview installed and adding a global.json file to force it to use .NET 10 made no difference.

global.json:

{ "sdk": { "version": "10.0.201" } }

What is causing this error? How do I fix it?

Read Entire Article