Search code examples
c#asp.net-core-webapi.net-8.0json-serialization

How to enable serializing for REST applications in ASP.NET Core 8?


In my project, the server returns the empty object while I have checked that this.taskGateway.RetrieveSelection returns the correct data:

[ApiController]
public class TaskController : ControllerBase
{
    private readonly TaskGateway taskGateway = FrontServerDependencies.Injector.gateways().Task;
  
    [HttpGet(TasksTransactions.RetrievingOfSelection.URN_PATH)]
    public async System.Threading.Tasks.Task<
      ActionResult<TaskGateway.SelectionRetrieving.ResponseData>
    > Get() 
    {
        return base.Ok(
            await this.taskGateway.RetrieveSelection(
                new TaskGateway.SelectionRetrieving.RequestParameters
                {
                    OnlyTasksWithAssociatedDate = onlyTasksWithAssociatedDate,
                    OnlyTasksWithAssociatedDateTime = onlyTasksWithAssociatedDateTime,
                    SearchingByFullOrPartialTitleOrDescription = searchingByFullOrPartialTitle
                })
        );
    }
}

AFAIK two things may be missed:

  1. Something has not been initialized in the entry point
  2. Something has been done wrong in the controller method

I was checking the official Microsoft tutorial.

No listing of entry point has been posted, so I needed to initialize the ASP.NET Core Web API project and check the Program.cs. Nothing related to JSON serializing has been mentioned:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

So, it looks like not the first one.

Checking the controller of the example:

using Microsoft.AspNetCore.Mvc;

namespace ASP_DOT_NET_CoreWebAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            }).ToArray();
        }
    }
}

The Get method returns the array of the objects. Again, nothing related to JSON serializing.

Why does this example work while my project - no?

The TaskGateway.SelectionRetrieving.ResponseData is:

struct ResponseData
{
    public required uint TotalItemsCount;
    public required uint TotalItemsCountInSelection;
    public required CommonSolution.Entities.Task[] Items;
}

Solution

  • From the documentation, these are the serialization behaviors:

    • By default, all public properties are serialized. You can specify properties to ignore. You can also include private members.

    • By default, fields are ignored. You can include fields.

    Hence, change the fields to properties as:

    struct ResponseData
    {
        public required uint TotalItemsCount { get; set; }
        public required uint TotalItemsCountInSelection { get; set; }
        public required CommonSolution.Entities.Task[] Items  { get; set; }
    }