Asp Net Web API 2.1 get client IP address

后端 未结 9 981
逝去的感伤
逝去的感伤 2020-11-27 11:12

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 ?

相关标签:
9条回答
  • 2020-11-27 11:45

    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;
        }
    
    0 讨论(0)
  • 2020-11-27 11:49

    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?

    0 讨论(0)
  • 2020-11-27 11:51

    Try to get the Ip using

    ip = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : "";
    
    0 讨论(0)
提交回复
热议问题