Asp.net web api 使用web api自托管获取客户端的IP地址

Asp.net web api 使用web api自托管获取客户端的IP地址,asp.net-web-api,owin,self-hosting,Asp.net Web Api,Owin,Self Hosting,自托管中不支持HttpContext 当我运行自托管内存集成测试时,此代码也不起作用: // OWIN Self host var owinEnvProperties = request.Properties["MS_OwinEnvironment"] as IDictionary<string, object>; if (owinEnvProperties != null) { return owinEnvProperties["server.RemoteIpAddress

自托管中不支持HttpContext

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

// OWIN Self host
var owinEnvProperties = request.Properties["MS_OwinEnvironment"] as IDictionary<string, object>;
if (owinEnvProperties != null)
{
    return owinEnvProperties["server.RemoteIpAddress"].ToString();
}
//OWIN自主机
var owinenproperties=request.Properties[“MS_OwinEnvironment”]作为IDictionary;
if(owinenproperties!=null)
{
返回owinenproperties[“server.RemoteIpAddress”].ToString();
}
OWINEnvProperty始终为空

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

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

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;
}
string ipAddress;
Microsoft.Owin.IOwinContext owinContext = Request.GetOwinContext();
if (owinContext != null)
{
    ipAddress = owinContext.Request.RemoteIpAddress;
}
或者,如果您不关心在上下文中测试空OWIN,您可以使用以下一行程序:

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

您使用的是“内存中”还是“自主机”?由于没有网络交互,执行“内存中”操作将没有IP地址。我的集成测试不会在主机中启动owin,而是在内存中测试web api请求管道。好的,我想我至少得到了localhost,但你是对的,从哪里应该得到它:p“因为没有网络交互”,那么我必须重新考虑我是想要使用新的HttpSelfHostServer(config).OpenAsync()进行快速内存测试还是真正的自主机测试。。。然后HttpServer除了bug和解决方法之外什么都没有给我。。。这只是MVC吗?