1

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;
}
4
  • Should be return Ok(await ...);? Commented Feb 4, 2024 at 6:50
  • 1
    @YongShun, Yes, you right, I have deleted it by mistake when boiled down the code. The actual code is including base.Ok(). Commented Feb 4, 2024 at 7:05
  • Just curious why you use struct in this case? Perhaps try adding the [Serializable] attribute, change those fields into properties with { get; set; }, or change it to a class type. Commented Feb 4, 2024 at 7:10
  • 1
    @YongShun AFAIK the structs are intended to be used instead of classes when they have only fields and properties but have no method. The response data or request parameters are exactly this case. But, if understood correctly the record concept, maybe it is better to replace the structs with records because the response data or request parameters are immutable. Commented Feb 4, 2024 at 7:14

1 Answer 1

1

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.