【问题标题】:Why JSON return value has changed when migrating from .net core 3.1 to .net 5为什么从 .net core 3.1 迁移到 .net 5 时 JSON 返回值发生了变化
【发布时间】:2021-09-08 17:29:35
【问题描述】:

我有一个 ASP.NET Web API,我已经从 .NET Core 3.1 迁移到 .NET 5,我的 JSON 中的返回值似乎因此而改变了。我环顾四周,但找不到任何关于为什么会发生这种情况的信息,我在下面包含了两个 JSON 返回值。

我只是发现这是一个问题,因为当我升级到 .NET 5 时,我的 Blazor API 调用抛出一个 JSON 异常,说它无法映射到模型,这很有意义,因为我已经从每个版本中拉回了 JSON在邮递员中。

任何帮助或信息将不胜感激。

C#代码

    // GET: api/a/get-all
    [HttpGet("get-all")]
    public async Task<IActionResult> GetAll()
    {
        var as = await _context.A.Include(p => p.PT)
                                          .Include(bt => bt.BT)
                                          .Include(bf => bf.BF)
                                          .Include(e => e.E)
                                          .Include(b => b.B)
                                          .Include(ar => ar.Ar)
                                          .Include(a => a.A)
                                          .Include(o => o.O)
                                          .Include(c => c.C)
                                          .Include(b => b.B)
                                          .ToListAsync();

        if (as == null)
            return NotFound(new { errorMessage = "It seems there are no A's in the database, please enter at least one." });

        return Ok(as);
    }

.Net Core 3.1

[
    {
        "id": 1,
        "propertyOne": "valueOne",
        "propertyTwo": "valueTwo"
    },
    {
        "id": 4,
        "propertyOne": "valueOne",
        "propertyTwo": "valueTwo"
    }
]

.Net 5

{
"$id": "1",
"$values": [
    {
        "$id": "2",
        "id": 1,
        "propertyOne": "valueOne",
        "propertyTwo": "valueTwo"
    },
    {
        "$id": "4",
        "id": 4,
        "propertyOne": "valueOne",
        "propertyTwo": "valueTwo"
    }
]

}

【问题讨论】:

  • Json是如何产生的?你的代码是什么?
  • 我已更新以包含 C# 代码,我已将表格重命名为单个字母。
  • 您的数据库模型和 Web 传输模型之间的分离似乎为零。不要那样做。为您的 Web 模型创建单独的实体,将您的数据库模型映射到它们,然后返回您的 Web 模型类。我不确定您的当前问题是什么,但如果您只是通过 API 抽出原始数据库模型,您将继续遇到这些问题。
  • 是的,目前并不真正关心 DTO,我已经保护了 API(无论如何它不会公开)。
  • 好吧,我告诉你的是你无法控制你传递的对象,所以你无法控制你生成的 JSON。因为这似乎是你的问题......一种可能的解决方案是拥有适当的 DTO 层。

标签: c# asp.net-core asp.net-web-api asp.net-core-3.1 .net-5


【解决方案1】:

我的 Blazor 项目在映射到模型时遇到问题,因为反序列化程序不期望 JSON 中的元数据。在我的 JsonSerializerOptions 中,我添加了 ReferenceHandler ReferenceHandler.Preserve 选项,这为我解决了这个问题。

JsonSerializerOptions options = new()
    {
        ReferenceHandler = ReferenceHandler.Preserve
    };

【讨论】:

    猜你喜欢
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2020-08-22
    • 2017-08-03
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多