I have tried digging and debugging but can't seem to figure out why Http.Json.GetFromJsonAsync isn't able to convert. The error that I get back is as follows (abridged)
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Onero.Shared.StudentDTO]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Onero.Shared.StudentDTO].
Here is my code:
// In the blazor wasm client
public async Task<IEnumerable<StudentDTO>> GetStudentsAsync()
{
return await http.GetFromJsonAsync<IEnumerable<StudentDTO>>("api/Students");
}
// My controller
[HttpGet]
public async Task<ActionResult<IEnumerable<StudentDTO>>> GetStudents()
{
return await _context.Students
.Select(x => StudentToDTO(x))
.ToListAsync();
}
// My classes
public class StudentDTO
{
public long ID { get; set; }
public string Name { get; set; }
public ICollection<ExamScores> Results { get; set; }
}
public class Student
{
public long ID { get; set; }
public string Name { get; set; }
public ICollection<Guardian> Guardians { get; set; }
public ICollection<ExamScores> Results { get; set; }
}
public class ExamScores
{
public long ID{ get; set; }
public long StudentId { get; set; }
public Student Student { get; set; }
public Exam ExamType { get; set; }
public double Score { get; set; }
}
// Startup.cs ConfigureServices
services.AddDbContext<ResultsContext>(opt =>
opt.UseSqlite(Configuration.GetConnectionString("FirstPrototype")));
services.AddControllersWithViews()
.AddJsonOptions(
x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve
);
// Context
public class ResultsContext : DbContext
{
public ResultsContext(DbContextOptions<ResultsContext> options)
: base(options)
{
}
public DbSet<ExamScores> ResultsList { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Guardian> Guardians { get; set; }
}
When I try logging the controller method, what I get back from _context is in fact
System.Collections.Generic.List`1[Onero.Shared.StudentDTO]
I am not sure if this is a problem with how I set up my database and migrations? Perhaps it has to do with the JsonSerializerOptionsin my ConfigureServices? But if it did, then why is my controller method reporting that I'm getting back a list of my object, yet my client can't deserialize it? I'd appreciate help/advice. Thanks