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!
You should be able to get it by doing the following:
OwinContext owinContext = (OwinContext)webapiHttpRequestMessage.Properties["MS_OwinContext"];
string ipaddress = owinContext.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