Search code examples
umbracowebapiumbraco8

Umbraco 8: Get all content of specific type in WebAPI class


Q) How do I access my website content, e.g. books collection in my WebAPI class?

In an Umbraco 8 website project, I am using the following in my razor view to get content, which works fine, allowing me to then iterate over the collection and build my page, all great.

@inherits Umbraco.Web.Mvc.UmbracoViewPage
@using ContentModels = Umbraco.Web.PublishedModels;
@using System.Text.RegularExpressions;


@{
    var books = Model.Root().DescendantsOfType("Book")
                .Cast<Book>().Where(x => x.ShowInWebsite);
}
//...

However, this doesn't compile in my WebAPI class - I don't know how to fix the references needed.

Error I'm getting:

The name 'Model' does not exist in the current context

Other things I've tried:

var books = Umbraco.ContentAtRoot().DescendantsOrSelf().OfTypes("Book");

// Which gives error:

IEnumerable<IPublishedContent>' does not contain a definition for 'DescendantsOrSelf' and the best extension method overload 'PublishedContentExtensions.DescendantsOrSelf(IPublishedContent, string)' requires a receiver of type 'IPublishedContent

Solution

  • Thanks to the comment by @Jannik Anker

    I managed to get my collection by so:

    var parent = Umbraco.ContentAtRoot().First().Children().FirstOrDefault(x => x.Name == "Booklist");
    if (parent != null) 
    {
        var books = parent.Children();
        var test = "";
        foreach (var book in books) 
        {
            test += book.Id + ": " + book.Name + "\r\n";
        }
        return test;
    }