Making a Variant Provider v3.1
Purpose | This page describes how to add variants to a Consumer App |
Prerequisites |
Overview
This tutorial runs through the process of creating a new Variant Provider that uses the time of day on the server to return a greeting that reflects the time of day.
This demonstrates how variants can be set within a consumer app.
Prerequisites
You should be familiar with how to create components, pages, variants, content definitions and content items in Forrit. Review the earlier sections in the documentation if this is not the case.
You should have completed the previous tutorial Making a Simple Consumer App, as this forms the starting point in Visual Studio
Configure Forrit page content:
Create three variants in Forrit, called "Morning", "Afternoon" and "Night".
Add a component to a page in Forrit, ensuring that the component is enabled for the three variants completed above.
Edit the page content so that the page displays different content for all variants, for example "Good Morning", "Good Afternoon" and "Good Evening".
Update .NET app
In Visual Studio, create a new class called
TimeOfDayVariantProvider
and ensure that it implementsIVariantProvider
:CODEpublic class TimeOfDayVariantProvider : IVariantProvider
In
TimeOfDayVariantProvider
, Implement the single required method ofIVariantProvider
:CODEpublic ValueTask<Guid> GetVariantAsync(CancellationToken cancellationToken = default) { string variant; DateTime systemDateTime = DateTime.Now; if (systemDateTime.Hour >= 0 && systemDateTime.Hour < 12) { variant = "{UID-for-morning-variant}"; } else if (systemDateTime.Hour >= 12 && systemDateTime.Hour < 18) { variant = "{UID-for-afternoon-variant}"; } else { variant = "{UID-for-night-variant}"; } return new ValueTask<Guid>(new Guid(variant)); }
This simple logic looks at the time of day on the server, and selects an appropriate variant based on that time.
In
Startup.cs
, replace this line at the end of theConfigureServices
function:CODEservices.AddSingleton<IVariantProvider, TimeOfDayVariantProvider>();
Run the application and check that the correct variant is selected and that the correct content is displayed in the website.
The new variant provider is now running in your Consumer App successfully.
Troubleshooting
Check that you have created a new release containing the updated pages, and that the release has been published to the correct consumer app
Check that the UIDs you used for variants in the Forrit Marketing Portal are the same as the UIDs your variant provider returns