Asp Net Web API 2.1 get client IP address

后端 未结 9 1035
逝去的感伤
逝去的感伤 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: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?

提交回复
热议问题