.net-coreazure-functionsisolation

How to get Client IP Address in Dotnet-Isolated Azure Functions?


I'm writing a function in .NetCore 6.0 (C#) using Azure Functions Isolation and need to get the ip address of the client. Is there any way to get Client IP address from the HttpRequestData OR FunctionContext object?

   [Function("GetClientIP")]
public async Task<HttpResponseData> GetClientIP([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req, FunctionContext functionContext)
{  ....  }

I have referred following link: but it is not for ISOLATION mode.

Remarks: I am using ISOLATION mode.


Solution

  • I was finally able to retrieve it by using the code below.

    Please note that the header value "x-forwarded-for" is only available when hosted within azure.

    public async Task<HttpResponseData> SendMessage(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req,
        FunctionContext executionContext, 
        string requestName)
    {
        var headerDictionary = req.Headers.ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);
        var key = "x-forwarded-for";
        if (headerDictionary.ContainsKey(key))
        {
            IPAddress? ipAddress = null;
            var headerValues = headerDictionary[key];
            var ipn = headerValues?.FirstOrDefault()?.Split(new char[] { ',' }).FirstOrDefault()?.Split(new char[] { ':' }).FirstOrDefault();
            if (IPAddress.TryParse(ipn, out ipAddress))
            {
                var ipAddressString = ipAddress.ToString();
            }
        }
    }
    

    In my case the retrieved value contained the following value "105.224.244.204, 147.243.88.136:58088" The first IP address in the list contains the client IP address.

    I also discovered that I could have retrieved it with key value "x-azure-clientip". The reason for this is the function is hosted behind Azure Front Door.

    The link goes into more detail about what headers can be expected on the request when hosted behind Azure Front Door https://learn.microsoft.com/en-us/azure/frontdoor/front-door-http-headers-protocol