Based on Asaff Belfer's answer, here's a couple of basic methods that I used to deploy this to an Azure Function (serverless / consumption plan) to obtain both the client IP and the client user agent. Also included a bit that is supposed to work in APIM, but have not tested that part yet. That information about APIM can be found at Stefano Demiliani's blog.
NOTE: these will return "(not available)" for local / self hosting. Someone can fix these to include self hosting, but I could not use those bits as the required Nuget packages from Asaff's answer (and others here) don't appear to work on the target framework I'm using (.NET 6.0).
public static string GetSourceIp(HttpRequestMessage httpRequestMessage)
{
string result = "(not available)";
// Detect X-Forwarded-For header
if (httpRequestMessage.Headers.TryGetValues("X-Forwarded-For", out IEnumerable<string> headerValues))
{
result = headerValues.FirstOrDefault();
}
//for use with APIM, see https://demiliani.com/2022/07/11/azure-functions-getting-the-client-ip-address
if (httpRequestMessage.Headers.TryGetValues("X-Forwarded-Client-Ip", out IEnumerable<string> headerValues2))
{
result = headerValues2.FirstOrDefault();
}
return result;
}
public static string GetClientUserAgent(HttpRequestMessage httpRequestMessage)
{
string result = "(not available)";
// Detect user-agent header
if (httpRequestMessage.Headers.TryGetValues("user-agent", out IEnumerable<string> headerValues))
{
result = string.Join(", ", headerValues);
}
return result;
}
Usage would be as follows:
string clientUserAgent = GetClientUserAgent(httpRequestMessage);
string clientIP = GetSourceIp(httpRequestMessage);
Hosted locally on my dev box using a Chrome browser, these returned:
User IP Address: (not available)
User Client: Mozilla/5.0, (Windows NT 10.0; Win64; x64), AppleWebKit/537.36, (KHTML, like Gecko), Chrome/108.0.0.0, Safari/537.36
Hosted in my serverless function in Azure commercial, using a Chrome browser, these returned:
User IP Address: 999.999.999.999:12345
(Of course, this is not a real IP address. I assume the 12345 part is a port number.)
User Client: Mozilla/5.0, (Windows NT 10.0; Win64; x64), AppleWebKit/537.36, (KHTML, like Gecko), Chrome/108.0.0.0, Safari/537.36