Get the client`s IP address using web api self hosting

asp.net-web-api, owin, self-hosting

Solution

Based on this, I think the more up-to-date 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 don't care about testing for a null OWIN context, you can just use this one-liner:

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

Problem

The HttpContext is not supported in self hosting. When I run my self hosted in-memory integration tests then this code does not work either: ``` // 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 am I supposed to get the client IP adress using self hosting?

Original source

Related problems