ContentRetriever API
Experimental API
This API is currently considered experimental. It uses the C# [Experimental]
attribute and is subject to change, potentially including breaking changes, in upcoming releases. Using this API will generate a compilation error by default, requiring you to explicitly opt-in by suppressing the specific diagnostic ID (e.g., using #pragma warning disable KXE0003
or project settings).
For more details on the attribute, see the Microsoft documentation.
Overview
IContentRetriever
provides a unified API to fetch various types of content managed by Xperience from within web applications. It’s intended as the primary service for the retrieval of:
- Pages
- Reusable content items
- Content sharing reusable field schemas
Functionally, the API servers as an abstraction layer over content query, where it handles common retrieval scenarios by providing default, recommended configuration for various aspects like query construction, language fallback handling, and linked item retrieval. However, it also provides developers the option to override these defaults by exposing parts of the retrieval lifecycle (e.g., query construction, model mapping) via function delegates.
This page introduces concepts shared by all methods available on the service, together with relevant examples. For a general method reference, see Reference - ContentRetriever API.
Shared aspects of the API
Configurable retrieval behavior
Certain overloads of IContentRetriever
methods accept an optional parameter object, named according to the retrieval scenario (e.g., RetrieveCurrentPageParameters, RetrievePagesParameters ). These objects allow you to configure the high-level behavior and scope of the content retrieval operation. They primarily control how and under what context data is fetched.
These parameter objects define behavior such as:
- The desired content language (
LanguageName
,UseLanguageFallbacks
). - Whether to retrieve preview or live content (
IsForPreview
). - The depth of linked content to include (
LinkedItemsMaxLevel
). - Whether to include pages requiring special permissions (
IncludeSecuredItems
). - Scope limitations like specific content tree paths (
PathMatch
) or workspaces (WorkspaceNames
).
When you call a retriever method without providing a specific parameters object – often by using the simpler extension method overloads – or if you provide a default instance (new RetrieveCurrentPageParameters()
for example), the API uses sensible defaults.
These defaults are designed for the most common use cases, typically relying on the current request’s context (e.g., using the detected preferred language, respecting the current preview mode status) and opting for safer, less resource-intensive settings (like LinkedItemsMaxLevel = 0
and IncludeSecuredItems = false
). This result in concise and performant queries.
The flexibility of this approach is in overriding the defaults when instantiating these objects. This allows you to tailor the retrieval to specific requirements. For example:
- You might need to display content in a specific language regardless of the user’s preference:
new RetrievePagesParameters { LanguageName = "spanish" }
- You might need to fetch related items linked from a main article:
new RetrieveCurrentPageParameters { LinkedItemsMaxLevel = 1 }
- You might need to ensure you’re always getting the latest, unpublished content:
new RetrieveContentParameters { IsForPreview = true }
- You might need to retrieve pages only within a specific section of the site:
new RetrievePagesParameters { PathMatch = PathMatch.Children("/products") }
By using these parameters objects, you gain explicit control over the retrieval context and scope, ensuring the retriever fetches the right content based on your application’s requirements, rather than just relying on implicit context or broad defaults.
Optional query configuration
Certain overloads of IContentRetriever
methods accept an additionalQueryConfiguration
parameter. The parameter allows you to directly configure the underlying content query builder instance. It gives you advanced control over the database query construction outside of what is accounted for by the query parameterization applied to the method.
You can use this to apply various query modifications, such as:
- Filtering – limiting results using Where conditions.
- Sorting – defining OrderBy clauses.
- Projection – specifying exact database columns to retrieve using Columns.
- Paging – limits results using:
- TopN – returns only the first
N
records according to the specified order. Cannot be combined withOffset
. - Offset – skips the first
offset
records and then retrieves the nextfetch
records. This is the recommended method for implementing paging and requires anOrderBy
clause to ensure consistent results. Cannot be combined withTopN
.
- TopN – returns only the first
- Linked items configuration – options for retrieving linked items via WithLinkedItems. Linked item depth is reflected from the corresponding method configuration object.
- Method-specific options – certain configuration options are unique to specific methods. For example,
UrlPathColumns
for page queries or InSmartFolder for content item queries.
Implicit result caching
Implicit caching functionality is not supported in the current version of the API.
While some method overloads require developers to provide a RetrievalCacheSettings
parameter, the only currently available option is to disable caching by passing RetrievalCacheSettings.CacheDisabled
.
If you plan to use this API in its current form, ensure caching for all results.
Custom model mapping
By default, content retriever methods use the default content query model mapping logic when populating the result.
Additionally, certain IContentRetriever
method overloads include an optional configureModel
parameter, which allows you to inject custom logic into the model mapping pipeline.
The paramater has the following signature:
Func<IContentQueryDataContainer, TInput, Task<TResult>> configureModel;
This parameter gives you control over how the retrieved data is mapped to your resulting model class.
IContentQueryDataContainer
– contains the database row (page, content item) being mapped. You can access column values viaGetValue<TValue>(string columnName)
.TInput
– the default mapping attempt to the type passed as the generic parameter to the corresponding content retriever method. For example, when calling:contentRetriever.RetrieveCurrentPage<ArticleGenerated>()
TInput
contains an instance ofArticleGenerated
for each mapped item from the result set. You can use this intermediate representation to fetch the data, run additional transformations (combining fields, for example) and any other custom logic.TResult
– the final type returned by the content retrieval operation. Determined by the type returned from theconfigureModel
delegate.
See the Run queries and map the result documentation to learn about the content item query model mapping lifecycle. IContentRetriever
methods simply expose certain parts of the lifecycle to plug into.
If you leave configureModel
as null
, the content retriever attempts a default mapping. It maps the columns retrieved from the database directly to the type supplied by the method generic. This usage is intended when using a generated model class that directly matches the underlying content type structure for the retrieved object.
// 'TResult' is 'ArticleGenerated' and the resulting data
// saturates an instance of 'ArticleGenerated'
//
// 'ArticleGenerated' is a model class generated by Xperience
// In this example, no custom model mapping applies, so the returned
// type corresponds to the type passed to 'RetrieveCurrentPage<TResult>'
ArticleGenerated article =
await contentRetriever.RetrieveCurrentPage<ArticleGenerated>();
Alternatively, you can provide a custom mapping function inside the configureModel
delegate. This function receives the raw data for each retrieved item in an IContentQueryDataContainer
object (which represents the database row data) and the intermediate mapped object (the type passed to the TResult
generic of the method). Inside this function, you can implement custom logic to instantiate and populate your desired return type. This allows you to transform the retrieved data to any custom C# model, combine fields, or shape the data exactly as required.
See the following simple demonstration on the RetrieveCurrentPage method.
using Kentico.Content.Web.Mvc;
// Example with custom mapping to a different model class
public class CustomArticleViewModel {
public string PageTitle { get; set; }
public string PageAdminTitle { get; set; }
}
// 'TResult' passed to 'RetrieveCurrentPage' is 'ArticleGenerated'
// and the resulting data saturates an instance of 'CustomArticleViewModel'
CustomArticleViewModel customViewModel =
await contentRetriever.RetrieveCurrentPage<ArticleGenerated>(
// Prepares a config object for the method initialized to default values
new RetrieveCurrentPageParameters(),
// No query modifications applied
null,
RetrievalCacheSettings.CacheDisabled,
// inside the 'configureModel' delegate, 'container' contains the
// raw database data, 'mappedResult' (TInput) is the mapping attempt to the
// 'TResult' model ('ArticleGenerated' model in this example) using
// the default query mapping logic (match columnName <=> propertyName)
async (container, mappedResult) =>
{
// Returns an object of a completely custom type,
// with arbitrary transformations applied
return new CustomArticleViewModel
{
PageTitle = mappedResult.Title ?? "Default Title",
PageAdminTitle = mappedResult.SystemFields.WebPageItemName ?? null
};
}
);
This mechanism offers flexibility, allowing simple mapping for standard cases and complex, custom transformations for advanced scenarios.
Method reference
See Reference - ContentRetriever API for a reference of all methods available on IContentRetriever
.