In this tutorial, you will learn how to retrieve a CMS page in code using Umbraco 8. Umbraco 8 introduced a big change in its core helpers. Gone are the days of accessing UmbracoContext
and the front-end cache through a singleton helper class. Accessing UmbracoContext
is now done with constructor injection.
IUmbracoContextFactory
There are a few different ways of getting data out of the CMS in V8. One useful and new approach is to use the IUmbracoContextFactory
. When Umbraco boots up, it will run all the necessary set-up code in the background so its core services can be accessed using dependency injection. This means accessing the core helpers is extremely easy. The IUmbracoContextFactory
can be injected into a controller - or a custom class - like so:
After having access to 'IUmbracoContextFactory', you can get access to a page within the content-tree, like so:
If you do not have the page ID, you can also get access to pages by its the content type instead, like so:
If you do not know the content type ID. You can also content by content type using the Alias
. If you are using ModelsBuilder you can get access to an alias like this contentType.Alias
:
Slightly bypassing good Umbraco 8 practices, if you are within your code and you need access to the current page, you can do this:
Using these techniques, you should be able to get a reference to any page that has been created within the Umbraco tree. Happy coding!