This is a quick post for those of you struggling to figure out how to get the URL for a page within Umbraco by code. Figuring out the friendly Url is something that you will need to do sooner rather than later when you're creating a website. You'll obviously need a menu, or you'll need to link to another page from within your view programmatically. In some situations, you will only have an IContent object to access which makes things a little tricky. IContent is useful when you need to update properties in your Umbraco environment, however, the IContent interface doesn't have an URL property. This is because Umbraco has two conceptual types, IContent which represents unpublished data and IPublishedContent which is used for displaying data on the frontend of the website. IContent is low as it involves database read/writes, published content is quicker as it uses the Lucene disk store.
IContent contnt = GET CONTENT; var urlProvider = Umbraco.Web.UmbracoContext.Current.UrlProvider; urlProvider .Mode = Umbraco.Web.Routing.UrlProviderMode.AutoLegacy; var url = urlProvider .GetUrl(contnt .Id);
When you only have an IContent, then you can use the UrlProvider to figure out the URL, as seen in the snippet above. If you need to get data this way, you may want to consider if your architecture is correct. If you can work with IPublishedContent instead, your code will be slightly more performant.