Hello I need get client IP that request some method in web api, I have tried to use this code from here but it always returns server local IP, how to get in correct way ?
If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:
private string getClientIp(HttpRequestMessage request = null)
{
if (request == null)
{
return null;
}
if (request.Properties.ContainsKey("MS_OwinContext"))
{
return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
}
return null;
}
Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.
Here's how I solved it:
using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
{
var hostname = HttpContext.Current.Request.UserHostAddress;
IPAddress ipAddress = IPAddress.Parse(hostname);
IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
...
Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?
Try to get the Ip using
ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";