Getting the Correct IP Address
Learn how to extract client IP addresses in Umbraco Engage by implementing a custom IP address extractor for specific server environments.
using Microsoft.AspNetCore.Http;
using Umbraco.Engage.Infrastructure.Analytics.Collection.Extractors;
public string? ExtractIpAddress(HttpContext context)
{
if (context?.Request?.Headers["X-Forwarded-For"].FirstOrDefault() is string ipAddresses)
{
var ipAddress = ipAddresses.Split(',')[0].Trim();
if (System.Net.IPAddress.TryParse(ipAddress, out _)) return ipAddress;
}
return context?.Connection?.RemoteIpAddress?.ToString();
}using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Engage.Infrastructure.Analytics.Collection.Extractors;
[ComposeAfter(typeof(Umbraco.Engage.Infrastructure.Analytics.Collection.Extractors.AnalyticsExtractorsComposer))]
public class CustomIpExtractorComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.Services.AddUnique<IHttpContextIpAddressExtractor, MyIpAddressExtractor>();
}
}Last updated
Was this helpful?