自托管不支持HttpContext。
当我运行自我托管的内存中集成测试时,此代码也不起作用:
// OWIN Self host
var owinEnvProperties = request.Properties["MS_OwinEnvironment"] as IDictionary<string, object>;
if (owinEnvProperties != null)
{
return owinEnvProperties["server.RemoteIpAddress"].ToString();
}
owinEnvProperties始终为null。
那么我应该如何使用自托管来获取客户端IP地址呢?
答案 0 :(得分:11)
基于this,我认为更新,更优雅的解决方案是执行以下操作:
string ipAddress;
Microsoft.Owin.IOwinContext owinContext = Request.GetOwinContext();
if (owinContext != null)
{
ipAddress = owinContext.Request.RemoteIpAddress;
}
或者,如果你不关心测试null OWIN上下文,你可以使用这个单行代码:
string ipAddress = Request.GetOwinContext().Request.RemoteIpAddress;
答案 1 :(得分:3)
const string OWIN_CONTEXT = "MS_OwinContext";
if (request.Properties.ContainsKey(OWIN_CONTEXT))
{
OwinContext owinContext = request.Properties[OWIN_CONTEXT] as OwinContext;
if (owinContext != null)
return owinContext.Request.RemoteIpAddress;
}