在处理较大的 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; }
}
使用 Postman 我得到以下结果。
https://localhost:7000/SchoolsV1
{
"schoolName": "My Elementary School"
}
然后
https://localhost:7000/SchoolsV2
{
"Students": [
{
"StudentID": "123456",
"FirstName": "Bill",
"LastName": "Smith",
"Grade": 4
},
{
"StudentID": "54321",
"FirstName": "Jane",
"LastName": "Doe",
"Grade": 5
}
],
"SchoolName": "My Elementary School"
}
这是预期的行为吗?使用 Results.Ok() 时我缺少什么吗?
Results.Ok
(这里实际上不需要,您可以只使用 app.MapGet("/SchoolsV1", () => school
)使用默认的 System.Text.Json
序列化器(有关它的更多信息可以在 docs 中找到),默认情况下不会序列化字段。有多种选择。
最简单的方法是将
School.Students
更改为属性:
public class School
{
public string SchoolName { get; set; }
public List<Student> Students { get; set; } = new List<Student>();
}
或者配置
Microsoft.AspNetCore.Http.Json.JsonOptions
:
builder.Services.Configure<JsonOptions>(opts => opts.SerializerOptions.IncludeFields = true);
var app = builder.Build();
// ...
对于 .net 7,这是我根据 Guru 的回答所做的。
builder.Services.AddControllers() .AddJsonOptions(选项=> { options.JsonSerializerOptions.IncludeFields = true; });
现在我的完整 json 对象返回而不是 { }