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?
You can self-host a web API in your own host process. New applications should use OWIN to self-host Web API. See Use OWIN to Self-Host ASP.NET Web API 2.
Client IP address can be retrieved via HttpContext. Connection object. This properties exist in both Razor page model and ASP.NET MVC controller. Property RemoteIpAddress is the client IP address.
getRemoteAddr() on the request object will give you the callers IP address.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With