When returning a class instance with public properties, an empty JSON object { } is returned. However, if I return a dynamic object, the expected response is returned. I'm using VS2019 with the latest patches. Steps to reproduce, create a ASP.NET Core Web API project and select .NET Core 3.1 (LTS) as the framework. Replace the contents of WeatherForecastController.cs with what I have included below and run the application.
using Microsoft.AspNetCore.Mvc;
namespace WebApplication3.Controllers
{
public class JsonResponse
{
public string Challenge;
public int Ttl;
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
public ActionResult Get()
{
JsonResponse rsp = new JsonResponse { Challenge = "challenge", Ttl = 1 };
return Ok(rsp); // returns { }
//return Ok(new { Challenge = "challenge", Ttl = 1 }); // returns { challenge: "challenge", ttl: 1 }
}
}
}
try to modify your JsonResponse class to make property contains declarations for a get and set accessor, like below.
public class JsonResponse
{
public string Challenge { get; set; }
public int Ttl { get; set; }
}
And as mentioned in this doc about "Serialization behavior", fields are ignored by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With