I have a very basic .NET API, where I query my Heartcore instance for recipes (which has an list of “ingredient section” elements, which has a heading and a list of ingredient elements.
using RecipePOC.Models;
using Umbraco.Headless.Client.Net.Delivery;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddUmbracoHeartcore(options => { options.AddModels(typeof(Program).Assembly); });
var app = builder.Build();
app.MapGet("/recipes", async (IContentDeliveryService client) =>
{
try
{
var recipes = await client.Content.GetByTypeAlias<Recipe>("recipe");
foreach (var recipe in recipes.Content.Items)
{
Console.WriteLine($"Recipe: {recipe.Name}");
Console.WriteLine($"Total Prep Time: {recipe.TotalPrepTime}");
Console.WriteLine($"Author: {recipe.Author}");
foreach (var section in recipe.IngredientSections)
{
Console.WriteLine($"Section: {section.Heading}");
foreach (var ingredient in section.Ingredients)
Console.WriteLine(
$"Ingredient: {ingredient.IngredientName}, Quantity: {ingredient.Quantity}, Unit: {ingredient.Unit}");
}
}
return Results.Ok(recipes?.Content.Items ?? []);
}
catch (Exception ex)
{
return Results.Problem($"Error retrieving recipes: {ex.Message}");
}
}).WithName("GetAllRecipes");
app.Run();
Models:
public class Recipe : Content
{
public string Name { get; set; }
public string TotalPrepTime { get; set; }
public string Author { get; set; }
public List<IngredientSection> IngredientSections { get; set; }
}
public class IngredientSection
{
public string Heading { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
public string IngredientName { get; set; }
public int Quantity { get; set; }
public string Unit { get; set; }
}
The “ingredientSections” array is being filled with the correct number of entries, but they are all empty. How can that be?
I’ve tried
public class IngredientSection
{
public string Heading { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
and
public class IngredientSection : Content
{
public string Heading { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
and
public class IngredientSection : Element
{
public string Heading { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
and also adding [ElementModel("ingredientSection")]
I’ve also tried using IEnumerable<>
instead of List<>