【问题标题】:Get the client`s IP address using web api self hosting使用 web api 自托管获取客户端的 IP 地址
【发布时间】:2014-02-21 05:18:27
【问题描述】:

自托管不支持 HttpContext。

当我运行自托管内存集成测试时,此代码也不起作用:

// OWIN Self host
var owinEnvProperties = request.Properties["MS_OwinEnvironment"] as IDictionary<string, object>;
if (owinEnvProperties != null)
{
    return owinEnvProperties["server.RemoteIpAddress"].ToString();
}

owinEnvProperties 始终为空。

那么我应该如何使用自托管获取客户端 IP 地址?

【问题讨论】:

  • 您使用的是“in-memory”还是“self-host”?做“in-memory”不会有IP地址,因为没有网络交互。
  • 我的集成测试不启动 owin 主机,而是在内存中测试 web api 请求管道。好的,我想我至少得到了 localhost 但你应该从哪里来:p
  • "因为没有网络交互" 然后我必须重新考虑我是想要快速内存测试还是使用 new HttpSelfHostServer(config).OpenAsync() 等进行真正的自主机测试......然后除了错误和解决方法之外,HttpServer 没有给我任何东西......

标签: asp.net-web-api owin self-hosting


【解决方案1】:

基于this,我认为更新和优雅的解决方案是执行以下操作:

string ipAddress;
Microsoft.Owin.IOwinContext owinContext = Request.GetOwinContext();
if (owinContext != null)
{
    ipAddress = owinContext.Request.RemoteIpAddress;
}

或者,如果您不关心空 OWIN 上下文的测试,您可以只使用这个单行:

string ipAddress = Request.GetOwinContext().Request.RemoteIpAddress;

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

    最近更新 更多