Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 955
Pascal Avatar asked Jan 29 '14 11:01

Pascal


People also ask

Can Web API be self hosted?

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.

How do I get client IP address in asp net core?

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.

How do I find my REST API IP address?

getRemoteAddr() on the request object will give you the callers IP address.


1 Answers

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;
like image 179
djikay Avatar answered Nov 07 '22 05:11

djikay