How To Get A Sitecore Items Url?
During a project, needing the current pages Url, or, linking to another page is a very common task. Sitecore provides several ways for developers to interact with the API in order to get different segments. In today's tutorial, I'm going to cover the basics of the different mechanisms in order to achieve this.
Sitecore Link ManagerThe LinkManager was introduced in Sitecore 6 and provides a fairly comprehensive set of features in dealing with urls. The link manager is a great way to get information about any Sitecore item. All you need to do is pass in the Item you want to query and set a few options and Sitecore will retrieve the Url for you. A very quick example of how to interact with the Link Manager can be seen below:
Item item; var url = Sitecore.Links.LinkManager.GetItemUrl(item);The link manager's GetItemUrl() method can also take in a number of configuration options, via an overload. The code below shows how to enable the 'AlwaysIncludeServerUrl' flag.
var urlOptions = new Sitecore.Links.UrlOptions(); urlOptions.AlwaysIncludeServerUrl = true; var pageUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Item, urlOptions);Setting this flag will now return the full Url, which looks like this:
http://www.website.com/terms-and-conditionsIf you are working on a multi-language site, you may want to get the current language branch within the Url, this can be achieved using the 'LanguageEmbedding ' property, like so:
var urlOptions = Sitecore.Links.UrlOptions.DefaultOptions; urlOptions.LanguageEmbedding = LanguageEmbedding.Always; var currenItem = Sitecore.Context.Item; var url = Sitecore.Links.LinkManager.GetItemUrl(currenItem, urlOptions1);When the LanguageEmbedding property is set, the Link Manager will return the following Url:
Raw UrlYou may sometimes just want to get information about the current request. You can do this without needing to get the current Sitecore object, or, the link manager. This can be done directly from the Sitecore context, using the RawUrl property:
var rawUrl = Sitecore.Context.RawUrl;This returns a result similar to the link manager with LanguageEmbedding enabled.
How To Get The Url For MediaWhen we need the Url for a media item, then we move away from the link manager and deal with the media manager. The media manager works in a similar manager as the link manager, you define some Url options and call the GetMediaUrl() method.
MediaItem item; var mediaUrlOptions= new MediaUrlOptions(); mediaUrlOptions.AlwaysIncludeServerUrl = true; var url = MediaManager.GetMediaUrl(item, mediaUrlOptions);