Retrieve content items

The Xperience API allows you to work with content items using the content query API and one of the following approaches:

  • Generated content type classes (recommended) – classes generated by the system that allow you to work with content type fields using strongly-typed objects. These classes also allow access to all general data (title, ID, GUID, creation date, publish date, etc.) as well.
  • Custom data transfer objects (advanced use case) – using custom classes grants you control over the data you map. Before using custom classes, make sure you are familiar with how the mapper API behaves. Also note that some Xperience APIs that work with content items expect certain system fields to be present in the model and will not work as expected otherwise. 

On this page, you will find information how to:

For more information about content querying and available parametrization, see Content item API and Reference - Content item query.

Retrieve content items

To retrieve content items, use the content query APIContentItemQueryBuilder and IContentQueryExecutor (available in the CMS.ContentEngine namespace) together with generated classes for individual content types. The generated content type classes allow you to work with strongly typed objects and easily access their fields.

Retrieve content items
// An instance of required services (e.g., obtained using dependency injection)
private readonly IContentQueryExecutor executor;
private readonly IContentQueryResultMapper mapper;

private async Task SampleContentQuery()
{
    // Configures the query builder to select 3 banners
    var builder = new ContentItemQueryBuilder()
                        .ForContentType(
                            "My.Banner",
                            config => config
                                .TopN(3)
                                .WithLinkedItems(1)
                        ).InLanguage("en");

    // Executes the configured query
    IEnumerable<Banner> query = await executor.GetResult(
												builder: builder,
                                                resultSelector: container => mapper.Map<Banner>(container));

    // Accesses the content item data
    foreach (Banner item in query)
    {
		// Accesses content type fields
        string header = item.BannerHeaderText;

		// Accesses system fields
	 	VersionStatus status = item.SystemFields.ContentItemCommonDataVersionStatus;
    }
}

Content item security

Content items can be secured to allow acces only for authenticated users. The secured state is indicated by the item.SystemFields.ContentItemIsSecured property. You can use this property to filter out secured content items during retrieval, or pass the property to a model and display information to visitors accordingly.

Reflect content item security in views
@model CompanyName.Models.MyModel

// In this case, 'ContentItemIsSecured' is mapped to the 'IsSecured' property of the view model 
@if (model.IsSecured && !User.Identity.IsAuthenticated)
{
	<p>
        Sign in to view this content.
	</p>
}

Both pages and content items use the same property to determine their security configuration. When working with collections of linked content items (provided, e.g., via a selection UI managed by the content item selector UI form component), you can determine which content items are marked as secured via simple projection.

Determine authentication requirements
// Contains a collection of sample 'Clinic' content items - retrieval code omitted for brevity
var clinic = await GetMedicalClinics();

var securedClinics = clinics.Select(x => x.SystemFields.ContentItemIsSecured);

Retrieve linked content items

To retrieve a list of content items linked to a page or another content item:

  1. Retrieve the object representing the content item or page containing linked content items using the content query API.
  2. Retrieve linked content items by accessing content item fields of the retrieved object.
Retrieve linked content items
// An instance of required services (e.g., obtained using dependency injection)
private readonly IContentQueryExecutor executor;
private readonly IContentQueryResultMapper mapper;

private async Task SampleContentQuery()
{
    // Configures the query builder to select 3 banners
    var builder = new ContentItemQueryBuilder()
                        .ForContentType(
                            "My.Banner",
                            config => config
                                .TopN(3)
                                .WithLinkedItems(1)
                        ).InLanguage("en");

    // Executes the configured query
    IEnumerable<Banner> query = await executor.GetResult(
												builder: builder,
                                                resultSelector: container => mapper.Map<Banner>(container));

    // Accesses the content item data
    foreach (Banner item in query)
    {
		// Accesses linked content item
        Image image = item.BannerBackgroundImage.FirstOrDefault();
		
		// Accesses content type fields of the linked item
        string description = image.ImageShortDescription;

		// Accesses system fields of the linked item
	 	VersionStatus status = image.SystemFields.ContentItemCommonDataVersionStatus;
    }
}

You can use the WithLinkedItems method to ensure that the linked items are loaded within the same database query as the retrieved content item. The maxLevel parameter controls the depth to which linked items are retrieved.

Retrieve assets

To retrieve information about an asset (e.g., filename, file size, URL) from a content item that has an asset field:

  1. Retrieve the object representing the content item or page containing linked content items using the content query API
  2. Retrieve a ContentItemAsset object from the asset field and access its properties.
Retrieve content item assets
// An instance of required services (e.g., obtained using dependency injection)
private readonly IContentQueryExecutor executor;
private readonly IContentQueryResultMapper mapper;

private async Task SampleContentQuery()
{
    // Configures the query builder to select 3 banners
    var builder = new ContentItemQueryBuilder()
                        .ForContentType(
                            "My.Banner",
                            config => config
                                .TopN(3)
                                .WithLinkedItems(1)
                        ).InLanguage("en");

    // Executes the configured query
    IEnumerable<Banner> query = await executor.GetResult(
												builder: builder,
                                                resultSelector: container => mapper.Map<Banner>(container));

    // Accesses the content item data
    foreach (Banner item in query)
    {
		// Accesses linked content item
        Image image = item.BannerBackgroundImage.FirstOrDefault();
		
		// Accesses the asset object in the ImageFile property of the Image content type
        ContentItemAsset asset = image.ImageFile;

		// Accesses properties of the asset
	 	string extension = asset.Metadata.Extension;
		string url = asset.Url;
    }
}

Secured assets

Content item assets that are configured to require authentication return HTTP 403 (Forbidden) when requested by unauthenticated visitors. In such cases, consider displaying a placeholder teaser image instead. For example, a popular practice is to display a blurred teaser image overlaid with a lock icon.