ASP.Net 核心 - 返回 JObject 时的空白响应 属性

ASP.Net core - blank response when returning a JObject property

我正在使用 ASP.Net 核心 5.0 并希望 return 对象的 IEnumerable 作为 Action 方法响应。

这是回复 class:

public class TestResponse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Newtonsoft.Json.Linq.JObject PayLoad { get; set; }
}

这是我的操作方法:

[HttpGet]
public IEnumerable<TestResponse> TestRequest()
{
    var testResponses = new List<TestResponse>();
    testResponses.Add(new TestResponse { Id = 10, Name = "Name1", PayLoad = JObject.FromObject(new { Status = "Success", Message = "Working good, take care!"})});
    testResponses.Add(new TestResponse { Id = 11, Name = "Name2", PayLoad = JObject.FromObject(new { Status = "Success", Message = "Working good, take care!" }) });

    return testResponses;
}

当我 运行 这样做时,我看到的 PayLoad 字段的响应是:

[
  {
    "id": 10,
    "name": "Name1",
    "payLoad": {
      "Status": [],
      "Message": []
    }
  },
  {
    "id": 11,
    "name": "Name2",
    "payLoad": {
      "Status": [],
      "Message": []
    }
  }
]

为什么 StatusMessage 字段为空?我错过了什么?

请添加如下包:

<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.17" />

你的 ConfigureServices 方法如下:

public void ConfigureServices(IServiceCollection services)
{
        
    services.AddControllersWithViews().AddNewtonsoftJson();
}

它对我有用。