Last active
June 12, 2023 08:12
-
-
Save mii9000/e7dc81805d77e4d6d8bc to your computer and use it in GitHub Desktop.
How to get Client IP from a request in Web API #webapi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net.Http; | |
using System.ServiceModel.Channels; | |
using System.Web; | |
using System.Web.Http; | |
namespace Trikks.Controllers.Api | |
{ | |
public class IpController : ApiController | |
{ | |
public string GetIp() | |
{ | |
return GetClientIp(); | |
} | |
private string GetClientIp(HttpRequestMessage request = null) | |
{ | |
request = request ?? Request; | |
if (request.Properties.ContainsKey("MS_HttpContext")) | |
{ | |
return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; | |
} | |
else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) | |
{ | |
RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)this.Request.Properties[RemoteEndpointMessageProperty.Name]; | |
return prop.Address; | |
} | |
else if (HttpContext.Current != null) | |
{ | |
return HttpContext.Current.Request.UserHostAddress; | |
} | |
else | |
{ | |
return null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not Working at server level