You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Minimal API中Results.Ok()无法返回完整对象的问题咨询

问题描述

开发大型Minimal API项目时,发现Results.Ok()无法返回完整对象,但切换为Results.Text()则能返回完整对象。以下是复现问题的简易代码:

using Newtonsoft.Json;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

School school = new School();
school.SchoolName = "My Elementary School";
school.Students.Add(new Student() { FirstName = "Bill", LastName = "Smith", Grade = 4, StudentID = "123456" });
school.Students.Add(new Student() { FirstName = "Jane", LastName = "Doe", Grade = 5, StudentID = "54321" });

app.MapGet("/SchoolsV1", () =>
{
    return Results.Ok(school);
});

app.MapGet("/SchoolsV2", () =>
{
    string strValue = JsonConvert.SerializeObject(school, Formatting.Indented);
    return Results.Text(strValue, "application/json", null);
});

app.Run();


public class School
{
    public string SchoolName { get; set; }
    public List<Student> Students = new List<Student>();
}
public class Student
{
    public string StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Grade { get; set; }
}

测试结果

访问/SchoolsV1(使用Results.Ok())返回:

{
    "schoolName": "My Elementary School"
}

访问/SchoolsV2(使用Results.Text()+Newtonsoft.Json序列化)返回完整对象:

{
    "Students": [
        {
            "StudentID": "123456",
            "FirstName": "Bill",
            "LastName": "Smith",
            "Grade": 4
        },
        {
            "StudentID": "54321",
            "FirstName": "Jane",
            "LastName": "Doe",
            "Grade": 5
        }
    ],
    "SchoolName": "My Elementary School"
}
原因分析与解决方案

这是序列化器的默认行为差异导致的,属于预期情况:

  • Minimal API默认使用System.Text.Json进行序列化,它默认只序列化带get/set的属性,不会序列化公共字段。你的School类中Students是无get/set的公共字段,因此被System.Text.Json忽略。
  • SchoolsV2使用Newtonsoft.Json序列化,它默认会序列化公共字段,因此能返回完整对象。

解决方法

有三种常见方案可选:

1. 将字段改为属性(推荐)

修改School类,把Students字段改为带get/set的属性:

public class School
{
    public string SchoolName { get; set; }
    public List<Student> Students { get; set; } = new List<Student>();
}

修改后System.Text.Json就能正常序列化Students数据。

2. 配置System.Text.Json序列化公共字段

在项目启动时,配置System.Text.Json支持序列化公共字段:

var builder = WebApplication.CreateBuilder(args);
// 配置序列化选项
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.IncludeFields = true;
});
var app = builder.Build();
// 后续代码不变

3. 切换到Newtonsoft.Json作为默认序列化器

如果项目依赖Newtonsoft.Json的其他特性,可安装Microsoft.AspNetCore.Mvc.NewtonsoftJson包,然后配置使用Newtonsoft.Json:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddNewtonsoftJson();
var app = builder.Build();
// 后续代码不变

内容的提问来源于stack exchange,提问作者user12376065

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:02:56