Search code examples
asp.net-coreasp.net-web-api.net-6.0

ASP.NET Core 6 Web API - serializing public fields


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?


Solution

  • Newer versions of aspnet use the json serializer from System.Text.Json by default instead of Newtonsoft.Json. By default the serializer of System.Text.Json will not serialize fields, unlike Newtonsoft.Json.

    The better option is to make the fields properties (e.g. public string Name { get; set; }). If that's really not an option you can adjust the settings of the serializer in your startup. E.g.

    builder.Services.AddControllers().AddJsonOptions(o =>
    {
        o.JsonSerializerOptions.IncludeFields = true;
    });