How To Get A Sitecore Items Url?
In any Sitecore project if we have to link one page to another page we would require a URL of the page. This is one of the common task that every developer will be performing. So in this tutorial, we will look at How to Get a Sitecore Items URL.
How to Get a Sitecore Items URL
From Sitecore 6.0 onwards LinkManager was introduced and through link manager, we can get a detailed information about the Sitecore item.
Sitecore Link Manager
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);
If we set the flag then the URl returned will be the complete URL. It will be something like this
If 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:
In Sitecore sometimes you need to get the Raw URL of current request or current item. In that case, you don’t have to use Sitecore Link Manager. You can get the Raw URL through Sitecore Context RawURL property.
var rawUrl = Sitecore.Context.RawUrl;
The Raw URL result will return something like this
How To Get The Url For MediaItems
When 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.
var mediaUrlOptions= new MediaUrlOptions();
mediaUrlOptions.AlwaysIncludeServerUrl = true;
var url = MediaManager.GetMediaUrl(item, mediaUrlOptions);
To obtain the URL of the media items we need to use MediaManager.GetMediaURL() method and the LinkManager doesn’t work under these situation.
Get URL in MVC Razor
If you are using MVC and want the current Url in a view, you can use the Model.Url property. Model.Url will return you ‘/products-landing’