Collect X-Forward-For in Azure Web App

  1. Create a web application and config Application Insights.

  2. Telemetry initializer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

namespace TestAppClientIp
{
public class CloneIPAddress : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
ISupportProperties propTelemetry = telemetry as ISupportProperties;

if (propTelemetry != null && !propTelemetry.Properties.ContainsKey("client-ip"))
{
string clientIPValue = telemetry.Context.Location.Ip;
propTelemetry.Properties.Add("client-ip", clientIPValue);
}
}
}
}
  1. Enable telemetry initializer for ASP.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using Microsoft.ApplicationInsights.Extensibility;

using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;

namespace TestAppClientIp
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

//Enable your telemetry initializer:
TelemetryConfiguration.Active.TelemetryInitializers.Add(new CloneIPAddress());
}
}
}
  1. Sending sample HTTP requests with X-Forwarded-For header or your custom header
1
Invoke-WebRequest "https://jackywin3.azurewebsites.net/About" -Method GET -Headers @{"X-Forwarded-For" = "1.1.0.1"}
  1. View the results of your telemetry initializer
    If you send new traffic to your site, and wait a few minutes. You can then run a query to confirm collection is working:
    requests
    | where timestamp > ago(1h)
    | project appName, operation_Name, url, resultCode, client_IP, customDimensions.[“client-ip”]

Application Insights ClientIP

For more information: https://docs.microsoft.com/en-us/azure/azure-monitor/app/ip-collection?tabs=net

Enjoy. 2020-9-23 By Jacky