Home > Software design >  ASP.Net core - blank response when returning a JObject property
ASP.Net core - blank response when returning a JObject property

Time:05-14

I am using ASP.Net core 5.0 and want to return IEnumerable of an object as Action method response.

Here is the response class:

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

This is my Action method:

[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;
}

When I run this, the response I see for PayLoad field is:

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

Why are the Status and Message fields blank? What am I missing?

CodePudding user response:

Please add package like below:

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

And your ConfigureServices method like below:

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

And it works for me.

enter image description here

  • Related