EN VI

C# - .NET 8 Web-API Returns empty List?

2024-03-13 15:00:05
How to C# - .NET 8 Web-API Returns empty List

I use a IActionResult to get a List. If I have a list, the result is ok. If I use a List, the elements of the result are empty.

If I use a generic List, it works:

public IActionResult GetData()
{
  var erg1 = _database.table.Select(x => new { x.Id, x.firstname, x.lastname });
  return Ok(erg1);
}

I get a List with all Elements:

[
  {
    "id": "732fdbd7-c878-45e8-8c43-5f795a697f6d",
    "firstname": "Uwe",
    "lastname": "Gabbert"
  },
  {
    "id": "5288f9ea-25a2-4ffc-a711-7c0b2cf49c38",
    "firstname": "User",
    "lastname": "Test"
  }
]

But, If I use a separate class for the elements, I get a empty List:

public IActionResult GetData()
{
    var erg2 = _database.table.Select(x => new User( x.Id, x.firstname, x.lastname ));
    return Ok(erg2);
}

In erg2 are 2 Items of User. But the return of getData is:

[
  {},
  {}
]

here the User-class:

public class User
{
    public string Id = "";
    public string Firstname = "";
    public string Lastname = "";

    public User(string id, string firstname, string lastname)
    {
        Id = id;
        Firstname = firstname;
        Lastname = lastname;
    }
}

Solution:

Your user class only contains fields, no properties. By default, only properties get serialized.

In the working case, you are instantiation anonymous types, not Users. Anonymous types by definition have properties, they don't support fields or methods.

To solve your problem, you can turn your fields into properties.

public class User
{
  public string Id { get; set; }
  public string Firstname { get; set; }
  public string Lastname { get; set; }

  public User(string id, string firstname, string lastname)
  {
    Id = id;
    Firstname = firstname;
    Lastname = lastname;
  }
}

As a sidenote, initializing either fields or properties to "" is spurious if you have a constructor that always assigns these values.

If you really don't want to use properties, you can configure the webapi json serializer to include fields. Note that this pretty non-standard and might confuse other people working with your code.

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

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login