How to get client IP address in Azure Functions C#

2020-01-29 08:01发布

问题:

I'm writing a function in C# using Azure Functions and need to get the ip address of the client that called the function, is this possible?

回答1:

Here is an answer based on the one here.

#r "System.Web"

using System.Net;
using System.Web;

public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log)
{
    string clientIP = ((HttpContextWrapper)req.Properties["MS_HttpContext"]).Request.UserHostAddress;
    return req.CreateResponse(HttpStatusCode.OK, $"The client IP is {clientIP}");
}


回答2:

you should use these function Get the IP address of the remote host

request.Properties["MS_HttpContext"] is not available if you debug precompiled functions local request.Properties[RemoteEndpointMessageProperty.Name] is not available on azure

private string GetClientIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;
    }

    if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
    {
        RemoteEndpointMessageProperty prop;
        prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];
        return prop.Address;
    }

    return null;
}

Update 21.08.2018: Now Azure Functions are behind a LoadBalancer --> we have to inspect Request-Headers to determine the correct Client IP

private static string GetIpFromRequestHeaders(HttpRequestMessage request)
    {
        IEnumerable<string> values;
        if (request.Headers.TryGetValues("X-Forwarded-For", out values))
        {
            return values.FirstOrDefault().Split(new char[] { ',' }).FirstOrDefault().Split(new char[] { ':' }).FirstOrDefault();
        }

        return "";
    }


回答3:

Now that Azure functions get an HttpRequest parameter, and they're behind a load balancer, this function to get the IP address works for me:

private static string GetIpFromRequestHeaders(HttpRequest request)
{
      return (request.Headers["X-Forwarded-For"].FirstOrDefault() ?? "").Split(new char[] { ':' }).FirstOrDefault();
}


回答4:

Update 18-Oct-2019:

The solution I tried is much easier and quicker and is mentioned below stepwise. But some more lengthy/tricky alternates are available @ https://docs.microsoft.com/en-us/azure/azure-monitor/app/ip-collection:

  1. Login into Azure portal.
  2. Open a new tab in same browser while you are logged in and dial “http://Resources.Azure.Com”
  3. This is Azure back end services portal so being slightly careful in making changes would be great.
  4. Expand SUBSCRIPTIONS section from the left panel and expand your Azure Subscription where app insight resource is located.
  5. Expand Resource Groups section and expand the Resource Group where app insights resource is.
  6. Expand the Providers section and find the Microsoft.Insights provider and expand it.
  7. Expand the Components section and find and select your App Insight Instance by name.
  8. On the right top change your mode to Read Write from Read Only.
  9. Click EDIT button on the Rest API call.
  10. ADD NEW “"DisableIpMasking": true property to properties section.
  11. Press PUT button to apply changes.
  12. Now your App Insight is enabled to start collecting Client IP addresses.
  13. Do some queries on the Function.
  14. Refresh and Test the App Insights data after about 5 to 10 minutes.