How do you go about getting the IP address of the remote client in a self-hosted SignalR hub? According to this question, you could at one point get it using Context.ServerVariables[], but that seems to be missing from the latest version of SignalR.
Well, in poking around in the recent commits on the SignalR project (specifically this one), I spotted how to do it.
protected string GetIpAddress()
{
var env = Get<IDictionary<string, object>>(Context.Request.Items, "owin.environment");
if (env == null)
{
return null;
}
var ipAddress = Get<string>(env, "server.RemoteIpAddress");
return ipAddress;
}
private static T Get<T>(IDictionary<string, object> env, string key)
{
object value;
return env.TryGetValue(key, out value) ? (T)value : default(T);
}
I didn't try it with the self-hosted SignalR Hub, but with SignalR 2.0, Context.Request
doesn't have the Items
anymore (at least not what I saw). I figured out, how it works now. (You can reduce the if / else part to a ternary operator, if you like that.)
protected string GetIpAddress()
{
string ipAddress;
object tempObject;
Context.Request.Environment.TryGetValue("server.RemoteIpAddress", out tempObject);
if (tempObject != null)
{
ipAddress = (string)tempObject;
}
else
{
ipAddress = "";
}
return ipAddress;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With