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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pascal
  • 12,265
  • 25
  • 103
  • 195
  • Are you using "in-memory" or "self-host" ? Doing "in-memory" will not have an IP address because there is no network interaction. – Darrel Miller Jan 29 '14 at 12:34
  • 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 :p – Pascal Jan 29 '14 at 13:23
  • "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... – Pascal Jan 30 '14 at 08:02

2 Answers2

11

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;
Krzyserious
  • 364
  • 4
  • 12
djikay
  • 10,450
  • 8
  • 41
  • 52
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;
}
metalheart
  • 3,740
  • 1
  • 23
  • 29
  • https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http.Owin/OwinHttpRequestMessageExtensions.cs Is this MVC only? – Pascal Jan 30 '14 at 08:14