Pascal
Pascal

Reputation: 12855

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

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?

Upvotes: 7

Views: 6919

Answers (2)

djikay
djikay

Reputation: 10628

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;

Upvotes: 12

metalheart
metalheart

Reputation: 3809

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;
}

Upvotes: 4

Related Questions