Get client IP address using native web API.

HttpContext is not supported in native hosting.

When I run my own memory integration tests, this code also does not work:

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

owinEnvProperties is always null.

So, how can I get the client IP address using my own hosting?

+6
source share
2 answers

Based on this , I think a more modern and elegant solution would be to do the following:

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

or, if you do not need to test the OWIN null context, you can simply use this single-line font:

string ipAddress = Request.GetOwinContext().Request.RemoteIpAddress;
+11
source
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;
}
+3
source

Source: https://habr.com/ru/post/1524271/


All Articles