首页 > 解决方案 > Umbraco 8:获取 WebAPI 类中特定类型的所有内容

问题描述

Q) 我如何访问我的网站内容,例如我的 WebAPI 类中的书籍收藏?

在 Umbraco 8 网站项目中,我在剃刀视图中使用以下内容来获取内容,效果很好,然后允许我遍历集合并构建我的页面,一切都很好。

@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);
}
//...

但是,这不能在我的WebAPI类中编译——我不知道如何修复所需的引用。

我得到的错误:

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

我尝试过的其他事情:

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

// 这给出了错误:

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

标签: umbracowebapiumbraco8

解决方案


您的 WebApi 类没有模型,但只要它继承自 UmbracoApiController 您应该能够做到

Umbraco.ContentAtRoot()...

反而?

https://our.umbraco.com/documentation/reference/routing/webapi/

根据https://our.umbraco.com/documentation/Reference/Querying/IPublishedContent/Collections/#oftypes你应该能够做到

Umbraco.ContentAtRoot().DescendantsOrSelf().OfTypes("Book")

推荐阅读