Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Remote Host IP in Web API Self-Hosted Using Owin

I need a very simple thing - get remote host IP address in Web API controller. This post describes how to do this when you are web hosting or self hosting. Unfortunately, the described solution does not work with Web API self-hosted using Owin (well, I couldn't make it work:)). I use windows service to host Web API.

So, the question is: How to get remote host IP address in Web API controller which is self-hosted in windows service using Owin?

Controller where I need remote IP address:

internal class ItemController : ApiController
{
    [HttpPost]
    public HttpResponseMessage AddItem([FromBody] string data)
    {
        // Need to get remote host IP address here

        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

Start up class that configures Web API:

internal class StartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var httpConfig = new HttpConfiguration();

        httpConfig.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(httpConfig);
    }
}

I use Windows service to host Web API. Below is the service's OnStart method:

    protected override void OnStart(string[] args)
    {
        var baseAddress = "http://localhost:5550/";
        // Start OWIN
        WebApp.Start<StartUp>( url: baseAddress );            
    }

Thank you!

like image 737
Nikolai Samteladze Avatar asked Nov 07 '13 22:11

Nikolai Samteladze


1 Answers

You should be able to get it by doing the following:

OwinContext owinContext = (OwinContext)webapiHttpRequestMessage.Properties["MS_OwinContext"];
string ipaddress = owinContext.Request.RemoteIpAddress;
like image 180
Kiran Avatar answered Oct 22 '22 06:10

Kiran