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 Manager
The 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:
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.
Setting this flag will now return the full Url, which looks 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:
When the LanguageEmbedding property is set, the Link Manager will return the following Url:
You 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:
This returns a result similar to the link manager with LanguageEmbedding enabled.
How To Get The Url For Media
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.
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 '/terms-and-conditions'
In today's guide, we've covered the main ways of getting Urls from Sitecore. In back-end code, the most common way is to use the Link Manager. The link manager has a number of properties that can be set to change which parts of a Url gets returned. you can get the whole server Url, or, only small segments depending on your requirements and needs. You can also get media items Url's, using the media manager.