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

Pas*_*cal 6 self-hosting asp.net-web-api owin

自托管不支持HttpContext.

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

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

owinEnvProperties始终为null.

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

dji*_*kay 11

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

string ipAddress;
Microsoft.Owin.IOwinContext owinContext = Request.GetOwinContext();
if (owinContext != null)
{
    ipAddress = owinContext.Request.RemoteIpAddress;
}
Run Code Online (Sandbox Code Playgroud)

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

string ipAddress = Request.GetOwinContext().Request.RemoteIpAddress;
Run Code Online (Sandbox Code Playgroud)


met*_*art 4

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;
}
Run Code Online (Sandbox Code Playgroud)