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

2

7

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?

Baronetage answered 29/1, 2014 at 11:59 Comment(3)
Are you using "in-memory" or "self-host" ? Doing "in-memory" will not have an IP address because there is no network interaction.Lumpfish
My integration tests do not start owin host but in-memory testing the web api request pipeline. Ok I thought I get at least localhost but you are right from where should it come :pBaronetage
"because there is no network interaction" Then I must really rethink wether I want fast in-memory testing or real self-host testing with new HttpSelfHostServer(config).OpenAsync() etc... Then the HttpServer gives me nothing except bugs and workarounds...Baronetage
D
12

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;
Digitalis answered 29/5, 2014 at 18:21 Comment(0)
G
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;
}
Gulf answered 29/1, 2014 at 12:28 Comment(1)
github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/… Is this MVC only?Baronetage

© 2022 - 2024 — McMap. All rights reserved.