Umbraco: How To Get The Url From An IContent

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 a 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 IConten, 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.

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *