Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  {
    "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;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading