Ich schreibe eine Funktion in C# mit Azure-Funktionen und muss die IP-Adresse des Clients, der die Funktion aufgerufen hat, erhalten, ist das möglich?Wie bekomme ich die Client-IP-Adresse in Azure-Funktionen C#?
10
A
Antwort
14
Hier ist eine Antwort basierend auf der 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}");
}
5
sollten Sie diese Funktion verwenden Get the IP address of the remote host
request.Properties [ "MS_HttpContext"] nicht verfügbar ist, wenn Sie vorkompilierte Funktionen debuggen lokalen request.Properties [RemoteEndpointMessageProperty.Name] ist nicht verfügbar auf azur
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;
}