Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DotNetCore 3.1 Web Api empty object response

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 }
        }   
    }
}
like image 728
bytez Avatar asked May 07 '26 15:05

bytez


1 Answers

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.

like image 185
Fei Han Avatar answered May 10 '26 13:05

Fei Han



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!