Sitecore: programmatically resolve URL from field value

I have a field that can contain an internal link, a media link, external links, etc. And we usually sort it by providing the sc: Link element and the corresponding field, and it resolves the URL accordingly.

What do I need to do if I want to resolve the URL programmatically (for serialization and sending via web service)?

I would really appreciate tips or pointers in the right direction.

+4
source share
2 answers

There is nothing in the Sitecore API that will provide what you need, but you can create a helper method to achieve what you need. I assume you are using LinkField .

Brian Pedersen's blog post has an article on Sitecore Links with LinkManager and MediaManager . The following is a snippet of code taken from his article:

 Sitecore.Data.Fields.LinkField lf = Sitecore.Context.Item.Fields["Link"]; switch (lf.LinkType.ToLower()) { case "internal": // Use LinkMananger for internal links, if link is not empty return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty; case "media": // Use MediaManager for media links, if link is not empty return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty; case "external": // Just return external links return lf.Url; case "anchor": // Prefix anchor link with # if link if not empty return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty; case "mailto": // Just return mailto link return lf.Url; case "javascript": // Just return javascript return lf.Url; default: // Just please the compiler, this // condition will never be met return lf.Url; } 

If you need to allow the internal URL to be fully consistent with the domain name, go to UrlOptions.SiteResolving=True to LinkManager .

+16
source
 string url = linkField.GetFriendlyUrl(); 

Where linkField is an instance of linkField .

+5
source

All Articles