In this tutorial, you will learn how to query Umbraco CMS for page related data. You might think that querying for data is simple, however, in V8 there are a number of different ways to query for content. I think that these different methods can make it confusing especially when you fail to get a code snippet you code online working and you are suddenly faced with an error The aim of this guide is to help you understand these nuances. The important thing to remember is that you query content from the frontend cache. The frontend cache can be accessed via the UmbracoContext. The front-end cache can be accessed using the Content property. If you look at its type, then you will see it is of type, IPublishedContentCache. You may naturally think a shortcut to accessing the content cache you be to inject this interface directly, you would be wrong.

If you tried to inject this interface an error would happen. Instead, you need to access the cache indirectly. In this tutorial, we will cover four different ways of accessing the cache, these are;

  • UmbracoHelper
  • IPublishedContentQuery
  • UmbracoContext
  • IUmbracoContextFactory

IPublishedContentQuery

Another way of accessing the cache is via IPublishedContentQuery. The code to do this looks like this;

Umbraco Helper

Another way of accessing the cache is via UmbracoHelper. The code to do this looks like this;

IUmbracoContextFactory

The safest way to access the front-end cache is to use the IUmbracoContextFactory. This can be done like this:

RenderMvcController

When you are within RenderMvcController, SurfaceController, or any of the other base types, then you can access the UmbracoContext using the exposed public property:

View

In a view, if the backing type inherits from UmbracoViewPage then you will have access to the UmbracoContext and UmbracoHelper. You only get access to both of these when you use inherit. If you use @model with a view model, you will not get access to either service. This is OK because following good MVC principles, all your logic should be added within a controller and passed down into the view: