I have a Model with ICollection:
public class Blog
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Posts> Posts { get; set; }
}
This works with MVC:
public async Task<IActionResult> Index()
{
return View(await _context.Blog.Include(l => l.Posts).ToListAsync());
}
I try to use API-Controller:
[Route("api/[controller]")]
[ApiController]
....
[HttpGet]
public IEnumerable<Blog> GetAll()
{
return _context.Blog.Include(l => l.Posts).ToList();
}
This generate a error:
SyntaxError: JSON.parse: end of data after property value in object at line 1 column 44 of the JSON data
How to return a multidimensional Json with Blogs and for every Blog entry all Posts?
Solution:
This is a error in JSON serialization.
Add in Startup.cs to Mvc ConfigureServices:
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
Try this
[Route("api/[controller]")]
[ApiController]
....
[HttpGet]
public IActionResult GetAll()
{
return Ok(_context.Blog.Include(l => l.Posts).ToList());
}
If you try async wrap IActionResult in Task