简体   繁体   English

当使用 LINQ GroupBy 时,ASP.NET 内核尝试将 object 转换为 System.Int64

[英]ASP.NET Core tries to cast an object to System.Int64 when using LINQ GroupBy

When trying to execute the following ASP.NET Core code:尝试执行以下 ASP.NET 核心代码时:

public class Foo
{
    public long A { get; set; }
    public string B { get; set; }
}

[HttpGet]
[Route("Foos")]
public ActionResult<IEnumerable<IGrouping<long, Foo>>> Foos()
{
    var foos = new List<Foo> { new Foo { A = 1, B = "Foo" }, new Foo { A = 2, B = "Bar" }, new Foo { A = 2, B = "Baz" } };
    return new ActionResult<IEnumerable<IGrouping<long, Foo>>>(foos.GroupBy(f => f.A));
}

I get:我得到:

System.InvalidCastException: Unable to cast object of type 'Foo' to type 'System.Int64'.
   at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWriteEnumerable(WriteStackFrame& current, Utf8JsonWriter writer)
   at System.Text.Json.JsonPropertyInfo.WriteEnumerable(WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.JsonSerializer.HandleEnumerable(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Why does it seem to be trying to serialize an object to an int64?为什么它似乎试图将 object 序列化为 int64? How can I successfully return the result of a GroupBy from a web API endpoint?如何从 web API 端点成功返回 GroupBy 的结果?

New System.Text.Json serializer cannot serialize IEnumerable<IGrouping<long, Foo>> .System.Text.Json序列化程序无法序列化IEnumerable<IGrouping<long, Foo>>

Solution解决方案

I would recommend switching to old Json.Net serializer in your ASP.Net Core project.我建议在您的 ASP.Net Core 项目中切换到旧的 Json.Net 序列化程序。 I've tested it and it works fine with Json.Net.我已经对其进行了测试,它可以与 Json.Net 一起正常工作。

See this article for information about switching to Json.Net.有关切换到 Json.Net 的信息,请参阅本文

It will be something as easy as that:事情就这么简单:

services.AddMvc()
    .AddNewtonsoftJson();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM