4
Vote

UpForGrabs: User IP Address in Web API RC

description

I've seen on various MS forums and Stack Overflow, the way to retrieve the user's IP address in Web API, requires falling back to the untestable (without mocking) static context object model by doing the following:

var ip = ((HttpContextWrapper) request.Properties["MS_HttpContext"]).Request.UserHostAddress;

or

var ip = ((HttpContextWrapper) request.Properties["MS_HttpContext"]).ServerVariables["REMOTE_ADDR"];

It seems counter to the very idea of Web API to have to return to using HttpContext.

Is this a temporary measure in the RC, or is there a better way to get this information?

comments

marcind wrote Aug 13, 2012 at 4:48 PM

We might want to introduce a context object that would attach to the request message that any host could populate with request-specific info that's not part of the http spec (such as client ip address, etc.)

HongmeiG wrote Mar 6 at 10:48 PM

We can add an extension method to retrieve the client address, like the way we did with IsLocal.

tugberk wrote Mar 7 at 8:35 AM

Yep, this is what I do now in my projects. I have a some sort of contract with my hosting layer and core API application that host would stick the user IP address inside the request.Properties bag and an extension method to retrieve that from the application layer as u indicated.

https://gist.github.com/tugberkugurlu/4683381

So, the default provided hosting options (asp.net and self) would stick this inside the properties bag and we are good to go.