Reputation: 11449
Is it possible to get the caller's IP address through the HubCallerContext? Or will I have to go through HttpContext.Current...ServerVariables to get it?
Upvotes: 12
Views: 20673
Reputation: 4686
Have you tried HttpContext.Request.UserHostAddress? See this example here: http://jameschambers.com/blog/continuous-communication-bridging-the-client-and-server-with-signalr
Don't think it's quite what you were hoping for, but should solve the problem nonetheless.
Upvotes: 0
Reputation: 509
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;
}
Upvotes: 31
Reputation: 4327
Other way is
var serverVars = Context.Request.GetHttpContext().Request.ServerVariables;
var Ip = serverVars["REMOTE_ADDR"];
Upvotes: 2
Reputation: 10606
According to source code no, there is no such property in HubCallerContext.
Upvotes: 1
Reputation: 20445
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.
Upvotes: 5