使用 Umbraco 获取特定类型的所有强类型文档

Get all strongly-typed document of a certain type with Umbraco

我有一个 Web 服务,我想在其中检索某种内容类型但作为强类型对象的所有文档。我试着用这个:

var contentType = Services.ContentTypeService.GetContentType(PensionPoint.ModelTypeAlias);
var points = Services.ContentService.GetContentOfContentType(contentType.Id).ToList();

但是,我得到了 IContent 对象,我无法对其执行 Object.Property。如何检索相同的项目但作为强类型对象?

您使用了错误的 Umbraco API,您需要使用 Umbraco Helper 来检索已发布的内容项目,而不是 returns 和 [=11= 的服务 API ]项。

var umbracoHelper = 
      new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var pensionPoints = 
      umbracoHelper.TypedContentAtRoot().First().Descendants<PensionPoint>();

当然,如果您的代码在控制器或视图中,您也许可以直接获取 UmbracoHelper 实例。

此外,请注意上面的代码假定您的内容位于单个 "home" 节点下。

最后,如果您的网站内容很多,性能可能不会很好,在这种情况下,您可能需要使用 XPATH 查询并将结果转换为您的 class。