如何从 EpiServer PageData 对象中提取友好的 URL?

How can I extract a friendly URL from an EpiServer PageData object?

使用 EpiServer 8.0,我们需要从 C# class 中的 PageData 对象获取 "friendly" URL。在不转换 URL 的情况下,内部链接看起来像 "localhost/link/[guid].aspx" 而不是 "localhost/friendly-link"。我在网上看到了以下建议:

var urlHelper = ServiceLocator.Current.GetInstance<UrlHelper>();
var friendlyUrl = urlHelper.ContentUrl(currentPage.Link);

但是当我尝试这样做时,Visual Studio returns 出现以下错误:

'System.Web.Mvc.UrlHelper' does not contain a definition for 'ContentUrl' and no extension method 'ContentUrl' accepting a first argument of type 'System.Web.Mvc.UrlHelper' could be found (are you missing a using directive or an assembly reference?)

这是我目前拥有的代码,没有使用语句,因此很容易看到正在使用的命名空间。

var urlHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<System.Web.Mvc.UrlHelper>();
var friendlyUrl = urlHelper.ContentUrl(myPage.Link);

我们的项目中是否缺少使 ContentUrl 起作用的引用?或者我们可以使用一些替代代码从 PageData 对象获取友好的 URL 吗?感谢您的帮助。

System.Web.Mvc.UrlHelper 没有 ContentUrl 方法。您可能正在考虑 UrlExtensions class.

UrlExtensions 在内部使用 EPiServer.Web.Routing.UrlResolver。您可以使用服务定位器(最好是构造函数注入)来获取 UrlResolver 的实例。然后你可以做urlResolver.GetUrl(myPage.ContentLink);

你应该使用 UrlResolver class

using System.Web.Routing;
using EPiServer.Web.Routing;

public static class PageDataExtensions
{

    public static VirtualPathData FriendlyUrl(this ContentReference contentReference)
    {
        return ServiceLocator.Current.GetInstance<UrlResolver>().GetVirtualPath(contentReference);
        // or use the singleton
        // return UrlResolver.Current.GetVirtualPath(contentReference); 
    }

    public static VirtualPathData FriendlyUrl(this PageData pageData)
    {
        var contentReference = pageData.ContentLink;
        return ServiceLocator.Current.GetInstance<UrlResolver>().GetVirtualPath(contentReference);
        // or use the singleton
        // return UrlResolver.Current.GetVirtualPath(contentReference); 
    }

    public static VirtualPathData FriendlyUrl(this IContent iContent)
    {
        var contentReference = iContent.ContentLink;
        return ServiceLocator.Current.GetInstance<UrlResolver>().GetVirtualPath(contentReference);
        // or use the singleton
        // return UrlResolver.Current.GetVirtualPath(contentReference); 
    }
}

这将 return 一个 VirtualPathData object that have the property VirtualPath

你的情况

var friendlyUrl = currentPage.FriendlyUrl().VirtualPath; // using the extensions above

会returnfriendly-url/whatever/page