为什么我自己无法访问 UmbracoHelper class

Why can I not access UmbracoHelper in my own class

我正在尝试在我自己的 class 中从 Umbraco 获取图像。

我不明白为什么我不能在 class 中使用 @umbraco 助手。我在class中定义了它的命名空间,比如:

using Umbraco.Core.Models;
using Umbraco.Web;

我只能使用 UmbracoHelper,当我写:

var umbracoHelper = new UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

这是我的 class:

using Umbraco.Core.Models;
using Umbraco.Web;

namespace House.Site.Helpers
{
    public static class ImageClass
    {
        public static string GetAbsoluteImageUrl(this IPublishedContent node, string propertyName)
        {
            var umbracoHelper = new UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

            var imgID = node.GetPropertyValue<string>("propertyName");
            var imgObject = umbracoHelper.TypedMedia(imgID);

            return imgObject.Url;
        }

    }
}

因为你的 class 没有继承自任何 Umbraco 基础 classes 你必须自己实例化 UmbracoHelper。

通过使用:

var umbracoHelper = new UmbracoHelper(UmbracoContext.Current)

非常好,可以让您访问所需的内容。

您应该可以只使用 UmbracoContext.Current 而不是完整的命名空间和 class 名称,因为您已经有了 Umbraco.Webusing 语句。

因为您需要一个助手实例才能使用它。你必须像你展示的那样实例化它,因为它依赖于一个有效的 UmbracoContext 而它又需要一个有效的 HTTP 上下文。在您的视图中使用助手时,这已经为您处理好,并且通过 class 您的视图继承的实例可用。

您可以在 Static references to web request instances (such as UmbracoHelper) 上的 Umbraco 文档中阅读有关此内容的更多详细信息。