(for EPiServer 8+)
…two simplified methods to cover LinkItem and Url:
public static ContentReference ToContentReference(this LinkItem linkItem) { if (linkItem == null) return ContentReference.EmptyReference; var content = UrlResolver.Current.Route(new UrlBuilder(linkItem.Href)); return content != null ? content.ContentLink : ContentReference.EmptyReference; }
And
public static ContentReference ToContentReference(this Url url) { if (url == null) return ContentReference.EmptyReference; var content = UrlResolver.Current.Route(new UrlBuilder(url)); return content != null ? content.ContentLink : ContentReference.EmptyReference; }
Source: Safest method of obtaining ContentReference from LinkItem