SignalR Get Caller IP Address

With SignalR 2.0, Context.Request doesn't have 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.)

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;
}

According to source code no, there is no such property in HubCallerContext.


The problem with HttpContext.Request.Current.UserHostAddress is that HttpContext.Request.Current is null if you're self-hosting.

The way you get it in the current version of SignalR (the 'dev' branch as of 12/14/2012) is like so:

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);
}

You used to be able to get it through Context.ServerVariables:

protected string GetIpAddress()
{
    var ipAddress = Context.ServerVariables["REMOTE_ADDR"];
    return ipAddress;
}

That was a lot simpler, but they removed it for reasons I don't entirely understand.