Retrieving A/B test variants in C#
Explore how to retrieve active A/B test variants for visitors using the Umbraco Engage C# API.
Last updated
Was this helpful?
Explore how to retrieve active A/B test variants for visitors using the Umbraco Engage C# API.
Last updated
Was this helpful?
Was this helpful?
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.Web;
using Umbraco.Engage.Infrastructure.AbTesting.Models;
using Umbraco.Engage.Infrastructure.AbTesting.Services.Interfaces;
using Umbraco.Engage.Infrastructure.Analytics.Collection.Visitor;
namespace Umbraco.Example;
public class ExampleService
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly IAnalyticsVisitorExternalIdHandler _externalIdHandler;
private readonly IAbTestingVisitorService _abTestingVisitorService;
public ExampleService(
IHttpContextAccessor httpContextAccessor,
IUmbracoContextAccessor umbracoContextAccessor,
IAnalyticsVisitorExternalIdHandler externalIdHandler,
IAbTestingVisitorService abTestingVisitorService)
{
_httpContextAccessor = httpContextAccessor;
_umbracoContextAccessor = umbracoContextAccessor;
_externalIdHandler = externalIdHandler ;
_abTestingVisitorService = abTestingVisitorService;
}
/// <summary>
/// Gets the active A/B test variants for the current visitor using GUID keys (recommended).
/// </summary>
/// <returns>Active <see cref="AbTestVariant"/>s for the visitor, or an empty list if unavailable.</returns>
public IEnumerable<AbTestVariant> GetCurrentVisitorActiveAbTestVariants()
{
if (_httpContextAccessor?.HttpContext is not HttpContext httpCtx ||
_externalIdHandler.GetExternalId(httpCtx) is not Guid externalId)
return [];
if (!_umbracoContextAccessor.TryGetUmbracoContext(out var umbCtx) ||
umbCtx.PublishedRequest?.Culture is not string culture ||
umbCtx.PublishedRequest?.PublishedContent is not IPublishedContent content)
return [];
// Using GUID-based overload (recommended)
return _abTestingVisitorService.GetVisitorAbTestVariants(
externalId,
content.Key,
content.ContentType.Key,
culture);
}
}