Last active
April 2, 2025 14:02
-
-
Save AThraen/e996e76423dfbe60ae5e3892220583f6 to your computer and use it in GitHub Desktop.
Add UTM Parameters to Optimizely CMS (Episerver) Forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using EPiServer.Forms.Core.VisitorData; | |
| using EPiServer.ServiceLocation; | |
| using Microsoft.Extensions.Primitives; | |
| namespace FormsFun.Business.Forms; | |
| [ServiceConfiguration(ServiceType = typeof(IVisitorDataSource))] | |
| public class UTMParametersDataSource(IHttpContextAccessor httpContextAccessor, ILogger<UTMParametersDataSource> logger) : IVisitorDataSource | |
| { | |
| //Remember to add services.AddHttpContextAccessor() in your startup / DI registration. | |
| private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); | |
| private readonly ILogger _logger = logger ?? throw new ArgumentNullException(nameof(logger)); | |
| public void SetData(ref object visitorData, string property) | |
| { | |
| var ctx = _httpContextAccessor?.HttpContext; | |
| if (ctx != null) | |
| { | |
| if (ctx.Request.Query[property] != StringValues.Empty) | |
| { | |
| visitorData = ctx.Request.Query[property].ToString(); | |
| return; | |
| } | |
| } | |
| else | |
| { | |
| _logger.LogWarning("Unable to get HttpContext when trying to get UTM parameters for form submission"); | |
| } | |
| visitorData = null; | |
| } | |
| public bool ClientSideMode => false; | |
| public string DataSourceName => "UTM Parameters"; | |
| public IEnumerable<KeyValuePair<string, string>> GetProperties() | |
| { | |
| List<KeyValuePair<string, string>> rt = new List<KeyValuePair<string, string>>(); | |
| rt.Add(new KeyValuePair<string, string>("utm_source", "UTM Source")); | |
| rt.Add(new KeyValuePair<string, string>("utm_medium", "UTM Medium")); | |
| rt.Add(new KeyValuePair<string, string>("utm_campaign", "UTM Campaign")); | |
| rt.Add(new KeyValuePair<string, string>("utm_term", "UTM Term")); | |
| return rt; | |
| } | |
| public async Task<object> SetDataAsync(string property) | |
| { | |
| object visitorData = null; | |
| SetData(ref visitorData, property); | |
| return visitorData; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment