Skip to content

NativeAot web core api custom error return code error System.Reflection.MissingMetadataException #2037

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lozn00 opened this issue Oct 14, 2022 · 6 comments

Comments

@lozn00
Copy link

lozn00 commented Oct 14, 2022

my code

builder.Services.AddControllers().ConfigureApiBehaviorOptions(setupAction => setupAction.InvalidModelStateResponseFactory = context =>
{
    var problemDetail = new Microsoft.AspNetCore.Mvc.ValidationProblemDetails(context.ModelState)
    {
        Type = "Error",
        Title = "Data Verify Error",
        Status = StatusCodes.Status200OK,
        Detail = "Please View Error",
        Instance = context.HttpContext.Request.Path
    };
    int count = problemDetail.Errors.Count;

    StringBuilder sb = new StringBuilder();
    sb.Append("Data Verify Error");

    foreach (KeyValuePair<string, string[]> kv in problemDetail.Errors)

    {

        StringBuilder s1 = new StringBuilder();
        for (int i = 0; i < kv.Value.Length; i++)
        {
            s1.Append(kv.Value[i] + " ");

        }
        sb.Append($"参数:{kv.Key}错误," + s1.ToString() + " ");
        //Console.WriteLine(kv.Key + kv.Value);

    }
    var result = new
    {
        code = -1,
        Status = StatusCodes.Status200OK,
        msg = sb.ToString()
    };
    problemDetail.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);
    return  new Microsoft.AspNetCore.Mvc.JsonResult(result);
});

How should I write the code to solve this error? I don't know anything about rd.xml syntax. I think rd.xml syntax is very complicated.

    System.Reflection.MissingMetadataException: 'System.Text.Json.Serialization.Converters.SmallObjectWithParameterizedConstructorConverter<<>f__AnonymousType6<System.Int32,System.Int32,System.String>,System.Int32,System.Int32,System.String,System.Object>' is missing metadata. For more information, please visit http://go.microsoft.com/fwlink/?LinkID=392859
         at System.Reflection.Runtime.General.TypeUnifier.WithVerifiedTypeHandle(RuntimeConstructedGenericTypeInfo, RuntimeTypeInfo[]) + 0x8f
         at System.Text.Json.Serialization.Converters.ObjectConverterFactory.CreateConverter(Type, JsonSerializerOptions) + 0x1e9
         at System.Text.Json.Serialization.JsonConverterFactory.GetConverterInternal(Type, JsonSerializerOptions) + 0x15
         at System.Text.Json.JsonSerializerOptions.GetConverterInternal(Type) + 0x21c
         at System.Text.Json.JsonSerializerOptions.DetermineConverter(Type, Type, MemberInfo) + 0x92
         at System.Text.Json.Serialization.Metadata.JsonTypeInfo.GetConverter(Type, Type, MemberInfo, Type&, JsonSerializerOptions) + 0x58
         at System.Text.Json.JsonSerializerOptions.<RootBuiltInConvertersAndTypeInfoCreator>g__CreateJsonTypeInfo|108_0(Type, JsonSerializerOptions) + 0x3a
         at System.Text.Json.JsonSerializerOptions.GetOrAddClass(Type) + 0x3e
         at System.Text.Json.JsonSerializerOptions.GetOrAddClassForRootType(Type) + 0x35
         at System.Text.Json.JsonSerializer.SerializeAsync(Stream, Object, Type, JsonSerializerOptions, CancellationToken) + 0x31
         at Microsoft.AspNetCore.Mvc.Infrastructure.SystemTextJsonResultExecutor.<ExecuteAsync>d__4.MoveNext() + 0x283
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) + 0xb9
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task) + 0x44
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeNextResultFilterAsync>g__Awaited|30_0>d`2.MoveNext() + 0xae
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x20
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceInvoker.ResultExecutedContextSealed) + 0x44

@jkotas
Copy link
Member

jkotas commented Oct 14, 2022

The best way to deal with this error is to switch to Json source generators for your Mvc types: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/source-generation?pivots=dotnet-7-0#source-generation-support-in-aspnet-core

@lozn00
Copy link
Author

lozn00 commented Oct 15, 2022

@jkotas I don't know how to read this document, there is too much information in it, can you combine the case, that is, my current error, to illustrate what code I should write to solve this error?

@lozn00
Copy link
Author

lozn00 commented Oct 15, 2022

This error came from inside the core web api, not from my own json entity class, so I have no idea how to write this code

@jkotas
Copy link
Member

jkotas commented Oct 15, 2022

builder.Services.AddControllers().
    AddJsonOptions(options => options.JsonSerializerOptions.AddContext<MyJsonContext>()). // Snippet from the documentation here
    ConfigureApiBehaviorOptions(setupAction => setupAction.InvalidModelStateResponseFactory = context =>
...
    // Change this to use concrete type
    return new Microsoft.AspNetCore.Mvc.JsonResult(new MyResult(-1,  StatusCodes.Status200OK, msg = sb.ToString()));
 });

...

// Definition of the concrete type
record MyResult(int code, int Status, string msg);

// Snippet from the documentation
[JsonSerializable(typeof(MyResult))]
internal partial class MyJsonContext : JsonSerializerContext { }

@lozn00
Copy link
Author

lozn00 commented Oct 15, 2022

thank you,is work My error probably comes from the fact that I defined a field instead of an attribute, so I return {}

@lozn00 lozn00 closed this as completed Oct 15, 2022
@lozn00
Copy link
Author

lozn00 commented Oct 15, 2022

It seems to work without defining MyJsonContext, thank you. My problem is that the class field should be changed to the attribute {get; set}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants