Search code examples
c#episerver

SimpleAddress from PropertyUrl


  1. I have certain page having both long (Page1/Page2/MyPage) and simple (MyPage) addresses.
  2. Then I want to reference it in certain place via PropertyUrl:

    [CultureSpecific]
    [Required]
    [BackingType(typeof(PropertyUrl))]
    [Display(
        Name = "Link",
        Description = "Link to the page",
        GroupName = SystemTabNames.Content,
        Order = 1)]
    public virtual Url Link { get; set; }
    
  3. I want the simple address (if it exists) to be used for the routing or url rendering but not the long one.

I am looking for some elegant solution for it if it exists


Solution

  • Got an answer from Brad McDavid

    Modified it a bit to fit better to my task:

    public static string GetExternalUrl(this Url url)
    {
        var content = UrlResolver.Service.Route(new UrlBuilder(url));
    
        return GetExternalUrl(content);
    }
    
    public static string GetExternalUrl(this ContentReference contentReference)
    {
        if (ContentReference.IsNullOrEmpty(contentReference)) return null;
    
        var content = ServiceLocator.Current.GetInstance<IContentLoader>().Get<IContent>(contentReference);
    
        return GetExternalUrl(content);
    }
    
    public static string GetExternalUrl(this IContent content)
    {
        var externalProperty = content?.Property["PageExternalURL"];
    
        return !string.IsNullOrWhiteSpace(externalProperty?.ToString()) ? $"/{externalProperty.ToString().Trim('/')}/" : null;
    }