Asp Net Web API 2.1 get client IP address

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

    My solution is similar to user1587439's answer, but works directly on the controller's instance (instead of accessing HttpContext.Current).

    In the 'Watch' window, I saw that this.RequestContext.WebRequest contains the 'UserHostAddress' property, but since it relies on the WebHostHttpRequestContext type (which is internal to the 'System.Web.Http' assembly) - I wasn't able to access it directly, so I used reflection to directly access it:

    string hostAddress = ((System.Web.HttpRequestWrapper)this.RequestContext.GetType().Assembly.GetType("System.Web.Http.WebHost.WebHostHttpRequestContext").GetProperty("WebRequest").GetMethod.Invoke(this.RequestContext, null)).UserHostAddress;

    I'm not saying it's the best solution. using reflection may cause issues in the future in case of framework upgrade (due to name changes), but for my needs it's perfect

提交回复
热议问题