4
votes

I have a field which can contain internal link, media link, external links etc and normally we sort it out by providing sc:Link the item and the respective field and it resolves the url accordingly.

If I wana resolve the url programmatically (to serialize and send over using web service) what do I need to do?

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

2
what do you mean by send over using web service? Do you already have have a service that you want to use? or build a new one?Pradeep Pati
building a new one. Donno how to resolve the url programatically thouser446923

2 Answers

16
votes

There is nothing in the Sitecore API directly that will achieve what you need but you can create a helper method to achieve what you require. I'm assuming you are using a LinkField.

There is a great article on Brian Pedersen's blog about Sitecore Links with LinkManager and MediaManager. Code snippet below 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 resolve the internal URL to be fully qualified with the domain name then pass in UrlOptions.SiteResolving=True to the LinkManager.

5
votes
string url = linkField.GetFriendlyUrl();

Where linkField is an instance of LinkField.