I have the requirement that my web controller needs to return a class with only public fields. E.g. I have
public class RunningScenario
{
public int Id;
public string Name;
}
and want to return this from my controller like this
[ApiController]
[Route("api/[controller]")]
public class ScenarioController : ControllerBase
{
[HttpPost("start")]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<RunningScenario>> StartScenario(int scenarioId)
{
// Error handling
var runningScenario = await _scenariorRunner.Start(scenarioId);
return Ok(runningScenario);
}
}
Though, running this just returns {}
instead of {"Id": 1, "Name": "Scenario 1"}
.
I also tried to add the [JsonInclude]
attribute to the fields, with no effect. The result is still an empty object.
So, my question is, how do I get the public fields to be serialized and deserialized?