HubCallerContextを介して発信者のIPアドレスを取得することは可能ですか?または、HttpContext.Current ... ServerVariablesを調べて取得する必要がありますか?
5 に答える
SignalR 2.0 では、もうContext.Request
ありませItems
ん (少なくとも私が見たものではありません)。私は今それがどのように機能するかを理解しました。(必要に応じて、if / else の部分を三項演算子に減らすことができます。)
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;
}
問題HttpContext.Request.Current.UserHostAddress
は、HttpContext.Request.Current
セルフホスティングの場合は null です。
現在のバージョンの SignalR (2012 年 12 月 14 日現在の「dev」ブランチ) で取得する方法は次のとおりです。
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);
}
あなたはそれを通り抜けることができましたContext.ServerVariables
:
protected string GetIpAddress()
{
var ipAddress = Context.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
それははるかに簡単でしたが、完全には理解できない理由で削除されました.
ソースコード番号によると、HubCallerContextにはそのようなプロパティはありません。
他の方法は
var serverVars = Context.Request.GetHttpContext().Request.ServerVariables;
var Ip = serverVars["REMOTE_ADDR"];
HttpContext.Request.UserHostAddress を試しましたか? ここでこの例を参照してください: http://jameschambers.com/blog/continuous-communication-bridging-the-client-and-server-with-signalr
それはあなたが望んでいたものではないと思いますが、それでも問題は解決するはずです。