【问题标题】:Umbraco 8: Get all content of specific type in WebAPI classUmbraco 8:获取 WebAPI 类中特定类型的所有内容
【发布时间】:2020-06-22 12:54:55
【问题描述】:

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

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

@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

【问题讨论】:

    标签: umbraco webapi umbraco8


    【解决方案1】:

    你的 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")
    

    【讨论】:

    • 我是否可以建议在官方文档中查看哪些方法可用? :-) 除非您已经尝试过,否则请查看our.umbraco.com/documentation/Reference/Querying/…
    • 也更新了我的答案 ;-)
    • 我也试过了 - 查看我更新后的问题以及您建议的行的输出。文档也无济于事——因为它们完全没有关于 webapi 实现的详细信息,实际上非常糟糕。谢谢。
    • @Dave 我没有看到尝试使用我建议的行。没有 .DescendantsOfType 但有一个 .DescendantsOrSelf() 可以与 .OfTypes("...") 结合使用?
    • 很公平!当然 ContentAtRoot() 是一个可枚举的,所以你必须在它之后抛出一个 .First() ,或者遍历它,也许将每个 DescendantsOrSelf() 等的结果添加到你自己的集合中?
    【解决方案2】:

    感谢@Jannik Anker 的评论

    我设法通过以下方式获得了我的收藏:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2022-11-04
      • 2017-11-06
      相关资源
      最近更新 更多